URLUtil = new function() { 
    this.resolveUrl = function(url) { 
        if (url && url.indexOf('~/') >= 0) 
            return url.replace('~/', '/'); 
        return url; 
    }
    this.accountHome = function(newUser) {
        if (newUser) return '/account/newuser?s_cid=RegistrationCodes';
        return '/account';
    }
				this.userMessage = function(template) {
					return this.resolveUrl('~/handlers/messages/' + template + '.aspx');
				}
}/*************************** _rjs.js ***************************/
if (typeof RJS == 'undefined') RJS = {};
RJS.Repeater = function(spec) {
//builds lists from arrays, customize templates by specifying spec.templates
var getTemplateName = function() {
return spec.templateName
};
var getClassName = function(ri) {
//adds class name to list item, by default it adds 'first' and 'last' based on the itemsPerRow spec value
switch (ri.index % spec.itemsPerRow) {
case 0:
return 'first';
case spec.itemsPerRow - 1:
return 'last';
default:
return '';
}
};
var itemCreated = function(ri) {
ri.templateName = spec.getTemplateName(ri);
ri.className = spec.getClassName(ri);
return ri;
};
var build = function(json, type) {
var iterator = function(n, i) {
var ri = spec.itemCreated({ spec: spec, index: i, json: n });
var template = spec.templates[ri.templateName];
if (!template) throw new Error('Repeater: Template named ' + ri.templateName + ' not found!');
var html = jQuery.processTemplateToText(template, n);
return html;
}
try {
var templateName = spec.getTemplateName(json, type);
} catch (e) {
window.console && console.log("Error getting template: ", e);
}
var template = spec.templates[templateName];
if (template && template.settings.isForArray) {
return jQuery.processTemplateToText(template, json);
}
return json.collect(iterator).join('');
};
var spec = Object.extend({
templates: RJS.Templates,
templateName: 'itemTemplate',
itemsPerRow: 4,
getTemplateName: getTemplateName,
getClassName: getClassName,
itemCreated: itemCreated
}, spec);
return {
buildString: build,
buildElements: function(json) { return new Element('ul').update(build(json)).childElements(); }
}
};
function arrayRemove(array, from, to) {
var rest = array.slice((to || from) + 1 || array.length);
array.length = from < 0 ? array.length + from : from;
return array.push.apply(array, rest);
};
RJS.Event = (function() {
var events = {};
return {
bind: function(eventName, handler) {
if (typeof events[eventName] === "undefined") {
events[eventName] = [];
}
events[eventName].push(handler);
},
unbind: function(eventName, handler) {
if (typeof handler === "undefined" && typeof events[eventName] !== "undefined") {
for (var i = 0; i < events[eventName].length; i++) {
if (events[eventName][i] == handler) {
arrayRemove(events[eventName], i);
}
}
} else if (typeof events[eventName] !== "undefined") {
delete events[eventName];
}
},
trigger: function(eventName, data) {
var stopPropagation = false,
e = {stopImmediatePropagation: function() {
stopPropagation = true;
}};
var retVal = true;
if (typeof events[eventName] !== "undefined") {
for (var i = 0; typeof events[eventName] !== "undefined" && i < events[eventName].length; i++) {
var result = events[eventName][i](data, e);
if (stopPropagation) {
return false;
}
if (typeof result !== 'undefined' && !!result)
retVal = false;
}
}
return retVal;
}
};
})();
// This method averages 20-50% faster (depending on the browser) than jQuery code to do the same in my tests
RJS.fastSelectorAll = function(tagName, className) {
if (document.querySelectorAll)
return document.querySelectorAll(tagName + "." + className);
var arrMatey = [];
var tags = document.getElementsByTagName(tagName.toLowerCase());
for (var i = 0; i < tags.length; i++) {
if (tags[i].className) {
var classes = tags[i].className.split(' ');
for (var j = 0; j < classes.length; j++) {
if (classes[j] == className)
arrMatey.push(tags[i]);
}
}
}
return arrMatey;
}
RJS.fastSelector = function(tagName, className) {
var items = RJS.fastSelectorAll(tagName, className);
if (items && items.length && items.length > 0) {
return items[0];
}
return null;
}
jQuery.expr[':'].external = function(a) {
return a.href && a.href.match(/https?\:/) && a.hostname && (a.hostname != location.hostname);
};
jQuery(function($) {
var anchors = $(""); // create empty jquery object to prevent jQuery from trying to query for links prematurely
anchors.selector = "a:external";
anchors.live("click", function(ev) {
if ($(this).hasClass("no-intercept")) {
return;
}
ev.preventDefault();
ev.stopPropagation();
window.open(this.href);
return false;
});
});
RJS.Watermark = function(ele, wm) {
if (!(ele = $(ele))) return;
var rm = function(event) {
if (ele.value != wm) return;
ele.value = "";
ele.removeClassName("watermark");
}
var add = function() {
if (ele.value != "") return;
ele.addClassName("watermark");
ele.value = wm;
}
ele.observe("focus", rm);
ele.observe("blur", add);
add();
};
/* Keeps a list to a certain size by removing older entries, FIFO */
RJS.Cache = function(_cacheSize) {
if (!_cacheSize) _cacheSize = 100;
var count = 0;
var resultsList = new Array();
var update = function(result) {
resultsList.unshift(result);
count++;
if (count == _cacheSize) {
resultsList.pop();
count--;
}
};
var clear = function() {
count = 0;
resultsList = new Array();
};
var _each = function(f) {
return resultsList.each(f);
};
return Object.extend({
update: update,
clear: clear,
_each: _each
}, Enumerable);
};
RJS.Cookie = {
set: function(name, value, expire, domain) {
if (expire) {
if (typeof expire === "number") {
var date = new Date();
date.setTime(date.getTime() + (expire * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else {
var expires = "; expires=" + expire.toGMTString();
}
}
else var expires = "";
if (domain) {
document.cookie = name + "=" + value + expires + "; path=/; domain=" + domain;
} else {
document.cookie = name + "=" + value + expires + "; path=/";
}
},
get: function(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
},
remove: function(name) {
RJS.Cookie.set(name, "", -1);
}
};
function trim(str, chars) {
return ltrim(rtrim(str, chars), chars);
}
function ltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
function padding(character, amount) {
var returnVal = [];
for (var i = 0; i < amount; i++) {
returnVal.push(character);
}
return returnVal.join('');
}
RJS.Mouse = { x: 0, y: 0 };
jQuery(document.body).mousemove(function(ev) {
RJS.Mouse.x = ev.pageX;
RJS.Mouse.y = ev.pageY;
});
RJS.isMouseOverElement = function(e, m) {
e = $(e);
m = m || RJS.Mouse;
var d = e.getDimensions(),
o = e.cumulativeOffset();
if (d.height == 0) {
var originalBorder = e.getStyle("border");
e.setStyle({ "border": "1px solid #fff" });
d = e.getDimensions();
o = e.cumulativeOffset();
if (originalBorder) {
e.setStyle({ "border": originalBorder });
} else {
e.setStyle({ "border": "none" });
}
}
var retVal = (m.y > o.top) && (m.y < (o.top + d.height)) && (m.x > o.left) && (m.x < (o.left + d.width));
return retVal;
};
function getQueryString(key, default_) {
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)return null;
return qs[1];
}
RJS.getQueryParam = function (key, default_) {
return getQueryString(key, default_);
};
(function ($) {
var timer = new function () {
var timer = {};
this.add = function (name, key, callback, interval) {
if (!timer[name]) timer[name] = {};
if (!timer[name][key]) timer[name][key] = [];
timer[name][key].push(setTimeout(callback, interval));
};
this.clear = function (name, key) {
if (!timer[name]) timer[name] = {};
if (!timer[name][key]) timer[name][key] = [];
while (timer[name][key].length > 0)
clearTimeout(timer[name][key].pop());
};
};
window.RJS.Timer = timer;
var UPDATE_INTERVAL = 30000;
var currentAssetID = null;
function assetRequest() {
var isPlaying = typeof RJS.Player != 'undefined' && typeof RJS.Player.player !== 'undefined' && RJS.Player.player != null && RJS.Player.player.isVideoPlaying && RJS.Player.player.isVideoPlaying();
if (!isPlaying) {
setTimeout(assetRequest, UPDATE_INTERVAL);
return true;
}
$.ajax({
complete: function () {
setTimeout(assetRequest, UPDATE_INTERVAL);
},
data: { aid: currentAssetID },
type: "POST",
url: URLUtil.resolveUrl('~/h/assetrequest')
});
return true;
}
var assetIdElem = document.getElementById("assetID");
if (assetIdElem) {
currentAssetID = assetIdElem.value;
setTimeout(assetRequest, UPDATE_INTERVAL);
}
$.fn.colorbox.standardOptions = {
login: {
href: URLUtil.resolveUrl("~/h/login"),
height: 335,
width: 500,
scrolling: false,
iframe: true,
transition: "none",
onLoad: function() {
$("#colorbox").addClass("login-modal");
},
onCleanup: function() {
setTimeout(function() { $("#colorbox").removeClass("login-modal"); }, 1);
}
},
userMessage: {
loginTitle: "DeferredRegistration",
height: 550,
width: 675,
scrolling: false,
iframe: true,
transition: "none"
}
};
$(document).ready(function () {
$(document).click(function (ev) {
var cb = $(ev.target).closest("a.colorbox");
if (cb.length > 0) {
cb.colorbox({ open: true, scalePhotos: true, maxHeight: 625, maxWidth: 900 });
ev.preventDefault();
ev.stopPropagation();
return false;
}
return true;
});
});
RJS.Confirm = function (options) {
var height = "200px";
if (options.height !== undefined) {
height = options.height;
}
var modalHtml = '<div class="inline-modal" id="remove-expired" >\
<p>' + options.message + '</p>\
<div class="buttonWrap">\
<a href="javascript:jQuery.fn.colorbox.close();" class="btn yesLarge">Ok</a>\
<a href="javascript:jQuery.fn.colorbox.close();" class="btn noLarge">Cancel</a>\
</div>\
</div>';
jQuery.fn.colorbox({
title: options.title,
html: modalHtml,
width: "450px",
height: height,
open: true
});
jQuery("a.btn.yesLarge").click(function (ev) {
ev.preventDefault();
jQuery.fn.colorbox.close();
options.callback();
return false;
});
return false;
};
RJS.Toast = function (title, text, displayTime, slideInDuration) {
displayTime = displayTime || 3000;
slideInDuration = slideInDuration || 700;
var toast = $(".statusAlert");
if (title && title.length > 0) {
toast.find("h2").html(title).show();
//toast.addClass("status");
} else {
toast.find("h2").hide();
//toast.removeClass("status");
}
toast.find("p").html(text);
toast.animate({
height: 'toggle'
}, slideInDuration, function () {
setTimeout(function () {
toast.animate({
height: 'toggle'
}, slideInDuration);
}, displayTime);
});
};
})(jQuery);
RJS.hotkeySequence = function(charOne, charTwo, callback) {
var k1 = charOne.toUpperCase().charCodeAt(0),
k2 = charTwo.toUpperCase().charCodeAt(0),
isCtrlPressed = false,
isInSequence = false,
CTRL = 17;
jQuery(document).keyup(function(e) {
if (e.which == CTRL) isCtrlPressed = false;
}).keydown(function(e) {
if (e.which == CTRL) isCtrlPressed = true;
else if (e.which == k1 && isCtrlPressed) {
isInSequence = true;
return false;
} else if (e.which == k2 && isCtrlPressed && isInSequence) {
callback();
isInSequence = false;
return false;
} else if (e.which !== CTRL) {
isInSequence = false;
}
});
}
RJS.typeSequence = function(string, callback) {
var currentIndex = 0;
var sequence = string.toLowerCase();
jQuery(document).keypress(function(e) {
var expectedCharCode = sequence.charCodeAt(currentIndex);
if (e.which === expectedCharCode) {
currentIndex++;
if (currentIndex === sequence.length) {
callback();
currentIndex = 0;
}
} else {
currentIndex = 0;
}
});
}
RJS.relativeFutureTime = function(future) {
var delta = future.getTime() - (new Date().getTime()),
hours = 0,
minutes = 0,
retVal = "";
if (delta > 3600000) {
hours = Math.floor(delta / 1000 / 60 / 60);
minutes = Math.floor((delta - (hours * 60 * 60 * 1000)) / 1000 / 60);
retVal = hours + " hour" + (hours > 1 ? "s" : "");
if (minutes > 1) {
retVal += " and " + minutes + " minute" + (minutes > 0 ? "s" : "");
}
return retVal;
}
if (delta < 60000) {
return delta < 1000 ? "one second" : Math.floor((delta / 1000) + " seconds");
}
if (delta < 120000) {
return "one minute";
}
return Math.floor(delta / 1000 / 60) + " minutes";
};
RJS.appendQueryParam = function(url, key, value) {
if (url.indexOf('?') > -1 && url.indexOf('#') === -1) {
return url + '&' + key + '=' + value;
} else if (url.indexOf('?') === -1 && url.indexOf('#') === -1) {
return url + '?' + key + '=' + value;
} else if (url.indexOf('?') > -1 && url.indexOf('#') > -1) {
var hashParts = url.split("#");
return hashParts[0] + '&' + key + '=' + value + '#' + hashParts[1];
} else {
var hashParts = url.split("#");
return hashParts[0] + '?' + key + '=' + value + '#' + hashParts[1];
}
}
//RJS.typeSequence("singleclick", function() {
//    RJS.allowDoubleFormSubmissions = !RJS.allowDoubleFormSubmissions;
//    if (RJS.allowDoubleFormSubmissions) {
//        var message = jQuery('<div style="position:fixed; top: 10%; left: 40%; text-align: center; z-index:100000; background: #FF8FAB; border: 4px solid #DE2F5A; color: #fff; width: 300px; height: 30px; -moz-border-radius: 10px; border-radius: 10px;padding:10px 0 0 0">Now allowing multiple form submissions.</div>');
//        jQuery('body').append(message);
//        setTimeout(function() {
//            jQuery(message).fadeOut(function() {jQuery(this).remove()});
//        }, 3000);
//    } else {
//        var message = jQuery('<div style="position:fixed; top: 10%; left: 40%; text-align: center; z-index:100000; background: #FF8FAB; border: 4px solid #DE2F5A; color: #fff; width: 300px; height: 30px; -moz-border-radius: 10px; border-radius: 10px;padding:10px 0 0 0">Now preventing multiple form submissions.</div>');
//        jQuery('body').append(message);
//        setTimeout(function() {
//            jQuery(message).fadeOut(function() {jQuery(this).remove()});
//        }, 3000);
//    }
//});
//RJS.allowDoubleFormSubmissions = false;
RJS.CancelEventOnPostback = function(e) {
var prm;
if (typeof Sys !== "undefined"
&& typeof Sys.WebForms !== "undefined"
&& typeof Sys.WebForms.PageRequestManager !== "undefined") {
prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm.get_isInAsyncPostBack()/* && !RJS.allowDoubleFormSubmissions*/) {
window.console && console.log("intercepted [", e.type, "]", e.which);
e.stopImmediatePropagation();
e.stopPropagation();
e.preventDefault();
return false;
}
}
}
jQuery(document)
.bind('keyup keydown keypress click mousedown mouseup touchStart touchEnd touchMove touchCancel', RJS.CancelEventOnPostback)
.keypress(function(e) {
var prm;
if (typeof Sys !== "undefined"
&& "WebForms" in Sys
&& "PageRequestManager" in Sys.WebForms
&& "getInstance" in Sys.WebForms.PageRequestManager) {
prm = Sys.WebForms.PageRequestManager.getInstance();
}
if (e.which === 13) {
var defaultButtons = jQuery(".defaultButton:visible");
if (defaultButtons.length > 0) {
var defaultButton = defaultButtons[0];
e.stopPropagation();
e.preventDefault();
if (prm) {
prm._activeDefaultButton = defaultButton;
prm._activeDefaultButtonClicked = false;
}
try {
if (defaultButton.click) {
defaultButton.click();
} else if (defaultButton.tagName.toLowerCase() === "a") {
jQuery(defaultButton).click();
location = defaultButton.href;
}
} finally {
if (prm) {
prm._activeDefaultButton = null;
}
}
return false;
}
}
});

/*************************** carousel.js ***************************/
// File Deleted

/*************************** ddroundies.js ***************************/

/*************************** jcarousellite_1.0.1.js ***************************/
// File Deleted

/*************************** jquery.easing.1.3.js ***************************/

/*************************** jquery.mask.js ***************************/

/*************************** jquery.validate.js ***************************/

/*************************** password.validate.js ***************************/
// File moved to /js/j/password.validate.js

/*************************** rjs.ad.js ***************************/
RJS.Player = {
"title": null
, "returnTitle": null
, "player": null
, "wrapper": null
, "ad": null
, "getNumberFromAttribute": function (attribute, fallbackValue) {
var parsedNumber;
try {
parsedNumber = parseInt(jQuery(RJS.Player.player).attr(attribute));
} catch (e) {
window.console && console.error && console.error(e);
return fallbackValue;
}
if (!parsedNumber) {
return fallbackValue;
}
return parsedNumber;
}
, "shrink": function () {
window.console && console.log(jQuery(RJS.Player.player).attr("data-disable-ad-resize"));
if (jQuery(RJS.Player.player).attr("data-disable-ad-resize") == "true") {
return;
}
var newWidth = 640;
var newHeight = 360;
//RJS.Player.player.flashResize(newWidth, newHeight);
RJS.Player.player.style.width = newWidth + "px";
RJS.Player.player.style.height = newHeight + "px";
RJS.Player.wrapper.style.marginLeft = "0";
RJS.Player.returnTitle.fadeIn();
RJS.Player.ad.fadeIn();
if (jQuery(".custom-channel-wrap").length > 0) {
jQuery(".custom-controls").hide();
}
}
, "grow": function () {
if (jQuery(RJS.Player.player).attr("data-disable-ad-resize") == "true") {
return;
}
var newHeight = RJS.Player.getNumberFromAttribute('data-original-height', 457),
newWidth = RJS.Player.getNumberFromAttribute('data-original-width', 768);
RJS.Player.ad.fadeOut();
//RJS.Player.player.flashResize(newWidth, newHeight);
RJS.Player.player.style.width = newWidth + "px";
RJS.Player.player.style.height = newHeight + "px";
RJS.Player.wrapper.style.marginLeft = "auto";
RJS.Player.returnTitle.fadeOut();
if (jQuery(".custom-channel-wrap").length > 0) {
jQuery(".custom-controls").show();
}
}
, "syncCountdown": function (remainder) {
RJS.Player.returnTitle.html("Your video will resume in <span>" + remainder + " seconds</span>");
}
, "init": function () {
if (!RJS.Player.player) {
RJS.Player.player = swfobject.getObjectById("playerwidget");
}
if (!RJS.Player.wrapper) {
RJS.Player.wrapper = document.getElementById("player-wrap");
}
if (!RJS.Player.title) {
RJS.Player.title = jQuery(".titlebar");
}
if (!RJS.Player.ad) {
RJS.Player.ad = jQuery('.tandemAd');
}
if (!RJS.Player.returnTitle) {
RJS.Player.returnTitle = jQuery('h2.return');
}
}
}
RJS.CompanionAdManager = function() {
var tile = null;
var player = null;
function start(data) {
RJS.Player.init();
if (data.isAd) {
RJS.Player.shrink();
renderAds(data.banners);
} else {
RJS.Player.grow();
}
}
function renderAds(html) {
var adContainer = jQuery("div.tandemAd > div");
adContainer.html(jQuery(html).children());
}
function syncCountdown(remainder){
RJS.Player.syncCountdown(remainder);
}
return {
start:start,
syncCountdown:syncCountdown
}
}();
RJS.AdManager = function() {
var ads = $H();
var add = function(id, options) {
ads.set(id, new RJS.Ad(id, options));
};
var get = function(id) {
return ads.get(id);
};
var reload = function(force) {
ads.each(function(n) {
if (force || n.value.options.autoLoad) {
n.value.renderTag();
}
});
};
var count = function() {
return ads.keys().length;
};
return {
reload: reload,
count: count,
add: add,
get: get
};
}()
RJS.Ad = Class.create({
initialize: function(id, options) {
this.id = id;
this.options = Object.extend({
autoLoad: true
, iframe: {
frameborder: 0
, className: 'ad'
, scrolling: 'no'
}
},
options
);
if (this.options.autoLoad) {
if (document.loaded) {
this.renderTag();
}
else {
document.observe('dom:loaded', this.renderTag.bindAsEventListener(this));
}
}
},
renderTag: function() {
$(this.id).update(new Element('iframe', this.options.iframe));
},
toQueryParams: function() {
var match = this.options.iframe.src.strip().match(/^([^;]+);(.*);?/);
if (!match) {
return {};
}
return {
"path": match[1]
, "params": match[2].split(';').inject({}, function(hash, pair) {
if ((pair = pair.split('='))[0]) {
var key = decodeURIComponent(pair.shift());
var value = pair.length > 1 ? pair.join('=') : pair[0];
if (value != undefined) {
value = decodeURIComponent(value);
}
if (key in hash) {
if (!Object.isArray(hash[key])) {
hash[key] = [hash[key]];
}
hash[key].push(value);
}
else {
hash[key] = value;
}
}
return hash;
})
}
},
toQueryPair: function(key, value) {
if (Object.isUndefined(value)) {
return key;
}
return key + '=' + encodeURIComponent(String.interpret(value));
},
toQueryString: function(queryParams) {
return queryParams.path + ";" + $H(queryParams.params).inject([], function(results, pair) {
var key = encodeURIComponent(pair.key), values = pair.value;
if (values && typeof values == 'object') {
if (Object.isArray(values)) {
return results.concat(values.map(this.toQueryPair.curry(key)));
}
} else {
results.push(this.toQueryPair(key, values));
}
return results;
}, this).join(';') + ";";
}
});

/*************************** rjs.community.js ***************************/
(function ($) {
//*** READY ***
$(document).ready(function () {
var commentsEnabled = RJS.Community.commentsEnabled;
var favoritesEnabled = RJS.Community.favoritesEnabled;
var ratingEnabled = RJS.Community.ratingEnabled;
var commentBox = $("#comments").find("textarea");
var charsRemaining;
var currentAssetID = null;
var assetIdElem = document.getElementById("assetID");
if (assetIdElem) {
currentAssetID = assetIdElem.value;
}
if (commentBox.length > 0) {
characterCounter(commentBox);
}
//*** RATINGS ***
$(".rated").mousemove(function (ev) {
if (!ratingEnabled) {
return;
}
var starWidth = 20;
var c = $(this); //context
if (c.hasClass('dimLight'))
return false;
c.find(".average").hide();
var userRating = c.find(".user");
var cursorPos = ev.pageX - c.offset().left;
userRating.show();
var ratingDOM = userRating.get(0);
if (ratingDOM) {
if (cursorPos < (starWidth * 1)) {
ratingDOM.className = 'rating user one';
ratingDOM.rev = '1';
} else if (cursorPos < (starWidth * 2)) {
ratingDOM.className = 'rating user two';
ratingDOM.rev = '2';
} else if (cursorPos < (starWidth * 3)) {
ratingDOM.className = 'rating user three';
ratingDOM.rev = '3';
} else if (cursorPos < (starWidth * 4)) {
ratingDOM.className = 'rating user four';
ratingDOM.rev = '4';
} else if (cursorPos < (starWidth * 5)) {
ratingDOM.className = 'rating user five';
ratingDOM.rev = '5';
} else {
ratingDOM.className = 'rating user';
userRating.removeAttr("rev");
}
}
}).mouseout(function (ev) {
if (!ratingEnabled) {
return;
}
var c = $(this); //context
var avgRating = c.find(".average");
var userRating = c.find(".user");
var rating = userRating.attr("rel");
var ratingDOM = userRating.get(0);
if (rating != null && ratingDOM) {
rating = parseInt(rating, 10);
switch (rating) {
case 1:
ratingDOM.className = 'rating user one';
break;
case 2:
ratingDOM.className = 'rating user two';
break;
case 3:
ratingDOM.className = 'rating user three';
break;
case 4:
ratingDOM.className = 'rating user four';
break;
case 5:
ratingDOM.className = 'rating user five';
break;
default:
ratingDOM.className = 'rating user';
userRating.hide();
avgRating.show();
break;
}
} else {
if (ratingDOM) {
ratingDOM.className = 'rating user';
}
userRating.hide();
avgRating.show();
}
}).click(function (ev) {
if (!ratingEnabled) {
RJS.Toast("", RJS.settingDisabledCopy, 5000);
return;
}
if (RJS.User.isSignedIn() === false) {
RJS.User.signIn({ returnUrl: location.href, loginTitle: "Rate", height: 355 });
return;
}
var c = $(this); //context
var userRating = c.find(".user").prop("rev");
if (userRating == null) {
return;
}
userRating = parseInt(userRating, 10);
c.find(".user").attr("rel", userRating.toString(10));
var data = {
rating: userRating,
assetID: currentAssetID,
userID: RJS.User.userID
};
$.ajax({
url: URLUtil.resolveUrl("~/h/rate?rating=" + data.rating + "&assetID=" + data.assetID + "&userID=" + data.userID),
type: "POST",
data: {},
cache: true
});
//Omniture call for submitting a rating
s.linkTrackVars = 'events'; s.linkTrackEvents = 'event2' + data.rating; s.events = 'event2' + data.rating; s.tl(this, 'o', data.rating + 'StarRating');
});
//*** POST A COMMENT ***
$("input.postComment").live("click", function () {
if (!commentsEnabled) {
RJS.Toast("", RJS.settingDisabledCopy, 5000);
return;
}
if (RJS.User.userInfoLoaded !== true) {
return false;
}
var commentArea = $(this).closest("fieldset");
communitySetup(function () {
if (RJS.User.hasSetupCommunity === false) {
commentArea.find("textarea").val("");
if (commentArea.hasClass("replyBox")) {
commentArea.remove();
}
return;
}
var data = {};
if (commentArea.find("input[name='replyTo']").length > 0)
data.repliedTo = commentArea.find("input[name='replyTo']").val();
data.commentTxt = commentArea.find("textarea").val();
data.assetID = currentAssetID;
data.userID = RJS.User.userID;
if ($.trim(data.commentTxt).length === 0) {
return false;
}
var urlStr = "assetID=" + data.assetID + "&userID=" + data.userID + "&commentTxt=" + data.commentTxt;
if (data.repliedTo)
urlStr += "&repliedTo=" + data.repliedTo;
RJS.Errors.clear("comments");
commentArea.find(".postComment").attr("disabled", "disabled").addClass("posting");
commentArea.find("textarea").attr("readonly", "readonly").addClass("posting");
$.ajax({
url: URLUtil.resolveUrl("~/h/assetComments?" + urlStr),
type: "POST",
cache: false,
data: {},
dataType: "json",
success: function (resp) {
if (resp.accepted !== 1) {
window.console && console.log(arguments);
CommentingError("<a href='javascript:;'>Temp</a>", 'Cannot Post Your Comment', resp.error);
if (resp.start) {
if (!resp.end)
resp.end = resp.start;
setSelectionRange(commentArea.find("textarea").get(0), resp.start, resp.end);
}
} else {
commentArea.find("textarea").val("");
var commentTemplate = jQuery.processTemplateToText(RJS.Templates.comment, { id: resp.commentID, flagged: "", userAlias: RJS.User.alias, createDate: toISO8601Timestamp(new Date()), comment: escapeHtml(data.commentTxt) });
commentTemplate = $(commentTemplate);
$("#commentsList").prepend(commentTemplate);
$("#emptyComments").remove();
commentTemplate.find(".commentTime").timeago();
var commentCounter = $("#commentCount span");
var commentsCount = commentCounter.text();
if (commentsCount !== "") {
commentsCount = parseInt(commentsCount, 10) + 1;
commentCounter.text(commentsCount);
} else {
commentsCount = 1;
commentCounter.parent().html("(<span>1</span>)");
}
$(".replyBox").remove();
//Omniture call for submitting a comment
s.linkTrackVars = 'events'; s.linkTrackEvents = 'event20'; s.events = 'event20'; s.tl(this, 'o', 'Comments');
}
},
error: function () {
window.console && console.log(arguments);
RJS.Errors.show("comments", "Your comment can not be posted at this time. Please try again later.");
},
complete: function () {
commentArea.find(".postComment").removeAttr("disabled").removeClass("posting");
commentArea.find("textarea").removeAttr("readonly").removeClass("posting");
}
});
});
return false;
});
$(".report").live("click", function () {
if (RJS.User.userInfoLoaded !== true) {
return false;
}
$.fn.colorbox({ iframe: true, innerWidth: 500, innerHeight: 500, scrolling: false, title: "Report Abuse", href: this.href });
return false;
});
$("a[rel='post_comment']").live("click", function () {
commentBox.focus();
});
//*** REPLY TO COMMENT ***
$("#comments a.reply").live("click", function () {
if (RJS.User.userInfoLoaded !== true) {
return false;
}
if (!commentsEnabled) {
RJS.Toast("", RJS.settingDisabledCopy, 5000);
return;
}
var commentContainer = $(this).closest(".comment");
var commentContainerid = commentContainer.context.parentNode.parentNode.id;
if (RJS.User.isSignedIn() === false) {
var returnUrl = RJS.appendQueryParam(location.href, "commentid", commentContainerid);
RJS.User.signIn({ returnUrl: returnUrl, height: 355, loginTitle: "Comment" });
return;
}
var replyBox = commentContainer.find(".replyBox");
if (replyBox.length === 0) {
replyBox = $('<fieldset class="replyBox">\
<textarea class="userReplyComment" name="userComment" rows="4" cols="40"></textarea>\
<input type="hidden" name="replyTo" />\
<input type="submit" class="btn postComment" value="" />\
<input type="submit" class="btn postCancel" value="" />\
<p>Remaining Character Count: <span class="charactersRemaining">500</span></p>\
</fieldset>');
commentContainer.append(replyBox);
}
var user = commentContainer.find("span.username").text();
replyBox.find("input[name='replyTo']").val(user);
var textbox = replyBox.find("textarea");
var textLengh = textbox.text("@" + user + ":").text().length;
setCaretToPos(textbox.get(0), textLengh);
characterCounter(textbox);
});
$("#comments .replyBox input.postCancel").live("click", function () {
$(this).closest(".replyBox").remove();
});
//*** TOGGLE FLAGGED COMMENTS ***
$("#comments .toggleVisibility").live("click", function () {
var link = $(this);
if (link.text() === "show") {
link.text("hide").closest(".comment").addClass("show");
} else {
link.text("show").closest(".comment").removeClass("show");
}
});
//*** LOAD COMMENTS ***
if (!commentsEnabled) {
jQuery("#commentsList").append('<div id="emptyComments"><p>' + RJS.settingDisabledCopy + '</p></div>');
} else {
var loadedComments = false;
var commentLoader = RJS.Video("commentsList", URLUtil.resolveUrl("~/h/assetComments?max=20&template=comment&aid=" + currentAssetID + "&sort=CreateDate DESC&r=" + Math.random()),
function (json) {
if (json.count !== 0) {
jQuery("#commentCount").html(" (<span>" + json.count + "</span>)");
jQuery(".commentTime").timeago();
} else {
jQuery("#commentsList").append('<div id="emptyComments"><p>Awesome – you can be the first to comment!</p></div>');
}
});
RJS.Tabs.tabFocused("comments", function () {
if (loadedComments === false) {
commentLoader.load();
loadedComments = true;
}
});
RJS.Community.loadComments = function () {
if (loadedComments === false) {
commentLoader.load();
loadedComments = true;
}
};
}
RJS.User.add_UserInfoLoaded(function () {
var commentid = RJS.getQueryParam("commentid", null);
if (commentid != undefined) {
var replylink = jQuery("#" + commentid).find("a.reply");
replylink.click();
}
})
var context = $('#bdy');
//*** ADD TO FAVORITES ***
context.on("click", "a.favorite.add", function () {
if (RJS.User.userInfoLoaded !== true) {
return false;
}
if (!favoritesEnabled) {
RJS.Toast("", RJS.settingDisabledCopy, 5000);
return false;
}
if (RJS.User.isSignedIn() === false) {
RJS.User.signIn({ returnUrl: location.href, loginTitle: "Feature", height: 355 });
return false;
}
var anchor = this;
var $anchor = $(this);
var assetID = this.rel;
var userID = RJS.User.userID;
var query = "userID=" + userID + "&assetID=" + assetID;
$anchor.removeClass("add").addClass("loading");
for (var i = 0; i < RJS.User.favorites.length; i++) {
if (RJS.User.favorites[i] === assetID) {
$anchor.removeClass("loading").addClass("added");
return false;
}
}
$.ajax({
type: "POST",
cache: false,
dataType: "json",
data: {},
url: URLUtil.resolveUrl("~/h/favorites?" + query),
error: function () {
window.console && console.log(arguments);
FavoritesError("<a href='javascript:;'>Temp</a>", "Unexpected error", "Your selection could not be added to your playlist at this time. Please try again later.");
$anchor.addClass("add");
},
success: function (resp) {
if (resp.accepted !== 1) {
window.console && console.log(arguments);
FavoritesError("<a href='javascript:;'>Temp</a>", "Whoa! Your Playlist is Full!", resp.error);
$anchor.addClass("add");
} else {
RJS.User.favorites.push(assetID);
$(".playlistAssetCount").text("(" + RJS.User.favorites.length + ")");
$anchor.addClass("added");
$anchor.removeAttr("tooltipid");
//Omniture call for adding to playlist
s.linkTrackVars = 'events'; s.linkTrackEvents = 'event28'; s.events = 'event28'; s.tl(this, 'o', 'Playlist');
RJS.Event.trigger("community.playlistUpdated");
}
},
complete: function () {
$anchor.removeClass("loading");
}
});
return false;
});
//*** ADD ALL EPISODES TO FAVORITES
context.on("click", ".addEpisode", function (ev) {
if (RJS.User.userInfoLoaded !== true) {
return false;
}
if (!favoritesEnabled) {
RJS.Toast("", RJS.settingDisabledCopy, 5000);
return false;
}
if (RJS.User.isSignedIn() === false) {
RJS.User.signIn({ returnUrl: location.href, loginTitle: "Feature", height: 355 });
return false;
}
ev.preventDefault();
ev.stopPropagation();
var $anchor = $(this).addClass("loading");
var titleName = this.title;
var assetCount = this.rev;
var titleID = this.rel;
var userID = RJS.User.userID;
var query = "userID=" + userID + "&titleID=" + titleID;
$.ajax({
type: "POST",
cache: false,
dataType: "json",
data: {},
url: URLUtil.resolveUrl("~/h/favorites?") + query,
error: function () {
window.console && console.log(arguments);
FavoritesError("<a href='javascript:;'>Temp</a>", "Unexpected error", "Your selection could not be added to your playlist at this time. Please try again later.");
},
success: function (resp) {
if (resp.accepted !== 1) {
window.console && console.log(arguments);
FavoritesError("<a href='javascript:;'>Temp</a>", "Woah! Your Playlist is Full!", resp.error);
} else {
for (var i = 0; i < resp.assets.length; i++) {
RJS.User.favorites.push(resp.assets[i]);
//Omniture call for adding to playlist
s.linkTrackVars = 'events'; s.linkTrackEvents = 'event28'; s.events = 'event28'; s.tl(this, 'o', 'Playlist');
}
$(".playlistAssetCount").text("(" + RJS.User.favorites.length + ")");
if (resp.assets.length > 0) {
RJS.Toast("Added " + assetCount + " episodes", " of " + titleName + " to your playlist.");
} else {
RJS.Toast("All episodes of ", titleName + " are already in your playlist.");
}
$anchor.html("Added All Episodes").removeClass("addEpisode").addClass("addedEpisode");
RJS.User.applyUserSettingsToAssets();
RJS.Event.trigger("community.playlistUpdated");
}
},
complete: function () {
$anchor.removeClass("loading");
}
});
return false;
});
});
function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}
function setCaretToPos(input, pos) {
setSelectionRange(input, pos, pos);
}
function TwoDigitPadding(number) { return number < 10 ? "0" + number : "" + number; }
function getCommentTimestamp() { // Returns a timestamp used to cache comments
var d = new Date();
if (RJS.Cookie.get("livecomments") === "true") return d.getTime();
return d.getUTCFullYear() + TwoDigitPadding(d.getUTCMonth() + 1) + TwoDigitPadding(d.getUTCDate()) + TwoDigitPadding(d.getUTCHours())
}
function toISO8601Timestamp(date) {
return date.getUTCFullYear() + "-"
+ TwoDigitPadding(date.getUTCMonth() + 1) + "-"
+ TwoDigitPadding(date.getUTCDate()) + "T"
+ TwoDigitPadding(date.getUTCHours()) + ":"
+ TwoDigitPadding(date.getUTCMinutes()) + ":"
+ TwoDigitPadding(date.getUTCSeconds()) + "Z";
}
function characterCounter(textBox) {
var charsRemaining = null;
function updateCharCount() {
var remaining = (500) - textBox.val().length;
if (!charsRemaining) {
charsRemaining = textBox.closest("fieldset").find(".charactersRemaining");
}
charsRemaining.text(remaining);
if (remaining < 0)
charsRemaining.addClass("error");
else
charsRemaining.removeClass("error");
}
$(textBox).bind("keyup keydown change blur", updateCharCount)
// When onPaste is triggered, it doesn't immediately give access to the textbox value
// in all browsers. Use a timeout that fires instantly to fix this
.bind("paste cut", function () { setTimeout(updateCharCount, 1); });
setTimeout(updateCharCount, 1);
}
function escapeHtml(html) {
return html.replace(/&/g, '&amp;')
.replace(/>/g, '&gt;')
.replace(/</g, '&lt;')
.replace(/"/g, '&quot;');
};
function communitySetup(callback) {
if (RJS.User.isSignedIn() && RJS.User.hasSetupCommunity === false) {
var firstRun = true;
$.fn.colorbox({
iframe: true,
href: URLUtil.resolveUrl("~/h/communitySetup"),
width: "500px",
innerHeight: 240,
onCleanup: function () {
if (firstRun === true) {
$(".aliasName").text(RJS.User.alias);
setTimeout(callback, 1);
firstRun = false;
}
},
scrolling: false,
transition: "none"
});
} else {
callback();
}
}
function CommentingError(elem, title, message) {
title = title || "Your Comment Cannot Be Posted";
message = message || "Sorry your comment does not meet the standards of our Community Terms of Service. Please modify it and try again.";
var errorMarkup = '<div>' + '<p>' + message + '</p>' + '<a href=\"javascript:jQuery.fn.colorbox.close();\" class=\"btn tryAgain\">try again</a>' + '</div>'
$(elem).colorbox({ title: title, html: errorMarkup, width: "475px", open: true });
}
function FavoritesError(elem, title, message) {
title = title || 'Whoa! Your Playlist is Full!';
message = message || 'If you want to add this video, you\'re going to have to delete something else. You can save up to 100 videos in your playlist at any time. ';
var errorMarkup = '<div>' + '<p>' + message + "</p>" + '<div class=\"buttonWrap clrbth group\"><input type=\"button\" class=\"btn managePlaylist\" onclick="return (function(){ location = URLUtil.resolveUrl(\'~/account/playlist\'); return false;})();" /><input type=\"button\" class=\"btn socialCancel\" onclick=\"javascript:top.jQuery.fn.colorbox.close();\" /></div>' + '</div>';
$(elem).colorbox({ title: title, html: errorMarkup, width: "475px", open: true });
}
$.extend(RJS.Community, {
flag: function (commentID) {
$("#" + commentID).addClass("flagged");
},
add_PlaylistUpdated: function (playlistUpdatedHandler) {
RJS.Event.bind("community.playlistUpdated", playlistUpdatedHandler);
}
});
})(jQuery);

/*************************** rjs.cryptography.js ***************************/
(function() {
// Public methods/objects:
//   RJS.Base64.encodeFromHex
//   RJS.Base64.decodeToByteArray
//   RJS.Base64.decodeToHex
//
//   RJS.RSAKey
//      .doPublic(x)
//      .setPublic(modulus, publicExponent)
//      .encrypt(text)
window.RJS = window.RJS || {};
RJS.Base64 = new function() {
var b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var b64pad = "=";
this.encodeFromHex = function(h) {
var i;
var c;
var ret = "";
for (i = 0; i + 3 <= h.length; i += 3) {
c = parseInt(h.substring(i, i + 3), 16);
ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
}
if (i + 1 == h.length) {
c = parseInt(h.substring(i, i + 1), 16);
ret += b64map.charAt(c << 2);
}
else if (i + 2 == h.length) {
c = parseInt(h.substring(i, i + 2), 16);
ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4);
}
while ((ret.length & 3) > 0) ret += b64pad;
return ret;
};
this.decodeToByteArray = function(s) {
var h = this.decodeToHex(s);
var i;
var a = new Array();
for (i = 0; 2 * i < h.length; ++i) {
a[i] = parseInt(h.substring(2 * i, 2 * i + 2), 16);
}
return a;
};
this.decodeToHex = function(s) {
var ret = ""
var i;
var k = 0; // b64 state, 0-3
var slop;
for (i = 0; i < s.length; ++i) {
if (s.charAt(i) == b64pad) break;
v = b64map.indexOf(s.charAt(i));
if (v < 0) continue;
if (k == 0) {
ret += int2char(v >> 2);
slop = v & 3;
k = 1;
}
else if (k == 1) {
ret += int2char((slop << 2) | (v >> 4));
slop = v & 0xf;
k = 2;
}
else if (k == 2) {
ret += int2char(slop);
ret += int2char(v >> 2);
slop = v & 3;
k = 3;
}
else {
ret += int2char((slop << 2) | (v >> 4));
ret += int2char(v & 0xf);
k = 0;
}
}
if (k == 1)
ret += int2char(slop << 2);
return ret;
};
};
// Copyright (c) 2005  Tom Wu
// All Rights Reserved.
// See "LICENSE" for details.
// Basic JavaScript BN library - subset useful for RSA encryption.
// Bits per digit
var dbits;
// JavaScript engine analysis
var canary = 0xdeadbeefcafe;
var j_lm = ((canary & 0xffffff) == 0xefcafe);
// (public) Constructor
function BigInteger(a, b, c) {
if (a != null)
if ("number" == typeof a) this.fromNumber(a, b, c);
else if (b == null && "string" != typeof a) this.fromString(a, 256);
else this.fromString(a, b);
}
// return new, unset BigInteger
function nbi() { return new BigInteger(null); }
// am: Compute w_j += (x*this_i), propagate carries,
// c is initial carry, returns final carry.
// c < 3*dvalue, x < 2*dvalue, this_i < dvalue
// We need to select the fastest one that works in this environment.
// am1: use a single mult and divide to get the high bits,
// max digit bits should be 26 because
// max internal value = 2*dvalue^2-2*dvalue (< 2^53)
function am1(i, x, w, j, c, n) {
while (--n >= 0) {
var v = x * this[i++] + w[j] + c;
c = Math.floor(v / 0x4000000);
w[j++] = v & 0x3ffffff;
}
return c;
}
// am2 avoids a big mult-and-extract completely.
// Max digit bits should be <= 30 because we do bitwise ops
// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
function am2(i, x, w, j, c, n) {
var xl = x & 0x7fff, xh = x >> 15;
while (--n >= 0) {
var l = this[i] & 0x7fff;
var h = this[i++] >> 15;
var m = xh * l + h * xl;
l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff);
c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30);
w[j++] = l & 0x3fffffff;
}
return c;
}
// Alternately, set max digit bits to 28 since some
// browsers slow down when dealing with 32-bit numbers.
function am3(i, x, w, j, c, n) {
var xl = x & 0x3fff, xh = x >> 14;
while (--n >= 0) {
var l = this[i] & 0x3fff;
var h = this[i++] >> 14;
var m = xh * l + h * xl;
l = xl * l + ((m & 0x3fff) << 14) + w[j] + c;
c = (l >> 28) + (m >> 14) + xh * h;
w[j++] = l & 0xfffffff;
}
return c;
}
if (j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
BigInteger.prototype.am = am2;
dbits = 30;
}
else if (j_lm && (navigator.appName != "Netscape")) {
BigInteger.prototype.am = am1;
dbits = 26;
}
else { // Mozilla/Netscape seems to prefer am3
BigInteger.prototype.am = am3;
dbits = 28;
}
BigInteger.prototype.DB = dbits;
BigInteger.prototype.DM = ((1 << dbits) - 1);
BigInteger.prototype.DV = (1 << dbits);
var BI_FP = 52;
BigInteger.prototype.FV = Math.pow(2, BI_FP);
BigInteger.prototype.F1 = BI_FP - dbits;
BigInteger.prototype.F2 = 2 * dbits - BI_FP;
// Digit conversions
var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
var BI_RC = new Array();
var rr, vv;
rr = "0".charCodeAt(0);
for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;
rr = "a".charCodeAt(0);
for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
rr = "A".charCodeAt(0);
for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
function int2char(n) { return BI_RM.charAt(n); }
function intAt(s, i) {
var c = BI_RC[s.charCodeAt(i)];
return (c == null) ? -1 : c;
}
// (protected) copy this to r
function bnpCopyTo(r) {
for (var i = this.t - 1; i >= 0; --i) r[i] = this[i];
r.t = this.t;
r.s = this.s;
}
// (protected) set from integer value x, -DV <= x < DV
function bnpFromInt(x) {
this.t = 1;
this.s = (x < 0) ? -1 : 0;
if (x > 0) this[0] = x;
else if (x < -1) this[0] = x + DV;
else this.t = 0;
}
// return bigint initialized to value
function nbv(i) { var r = nbi(); r.fromInt(i); return r; }
// (protected) set from string and radix
function bnpFromString(s, b) {
var k;
if (b == 16) k = 4;
else if (b == 8) k = 3;
else if (b == 256) k = 8; // byte array
else if (b == 2) k = 1;
else if (b == 32) k = 5;
else if (b == 4) k = 2;
else { this.fromRadix(s, b); return; }
this.t = 0;
this.s = 0;
var i = s.length, mi = false, sh = 0;
while (--i >= 0) {
var x = (k == 8) ? s[i] & 0xff : intAt(s, i);
if (x < 0) {
if (s.charAt(i) == "-") mi = true;
continue;
}
mi = false;
if (sh == 0)
this[this.t++] = x;
else if (sh + k > this.DB) {
this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh;
this[this.t++] = (x >> (this.DB - sh));
}
else
this[this.t - 1] |= x << sh;
sh += k;
if (sh >= this.DB) sh -= this.DB;
}
if (k == 8 && (s[0] & 0x80) != 0) {
this.s = -1;
if (sh > 0) this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh;
}
this.clamp();
if (mi) BigInteger.ZERO.subTo(this, this);
}
// (protected) clamp off excess high words
function bnpClamp() {
var c = this.s & this.DM;
while (this.t > 0 && this[this.t - 1] == c) --this.t;
}
// (public) return string representation in given radix
function bnToString(b) {
if (this.s < 0) return "-" + this.negate().toString(b);
var k;
if (b == 16) k = 4;
else if (b == 8) k = 3;
else if (b == 2) k = 1;
else if (b == 32) k = 5;
else if (b == 4) k = 2;
else return this.toRadix(b);
var km = (1 << k) - 1, d, m = false, r = "", i = this.t;
var p = this.DB - (i * this.DB) % k;
if (i-- > 0) {
if (p < this.DB && (d = this[i] >> p) > 0) { m = true; r = int2char(d); }
while (i >= 0) {
if (p < k) {
d = (this[i] & ((1 << p) - 1)) << (k - p);
d |= this[--i] >> (p += this.DB - k);
}
else {
d = (this[i] >> (p -= k)) & km;
if (p <= 0) { p += this.DB; --i; }
}
if (d > 0) m = true;
if (m) r += int2char(d);
}
}
return m ? r : "0";
}
// (public) -this
function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this, r); return r; }
// (public) |this|
function bnAbs() { return (this.s < 0) ? this.negate() : this; }
// (public) return + if this > a, - if this < a, 0 if equal
function bnCompareTo(a) {
var r = this.s - a.s;
if (r != 0) return r;
var i = this.t;
r = i - a.t;
if (r != 0) return r;
while (--i >= 0) if ((r = this[i] - a[i]) != 0) return r;
return 0;
}
// returns bit length of the integer x
function nbits(x) {
var r = 1, t;
if ((t = x >>> 16) != 0) { x = t; r += 16; }
if ((t = x >> 8) != 0) { x = t; r += 8; }
if ((t = x >> 4) != 0) { x = t; r += 4; }
if ((t = x >> 2) != 0) { x = t; r += 2; }
if ((t = x >> 1) != 0) { x = t; r += 1; }
return r;
}
// (public) return the number of bits in "this"
function bnBitLength() {
if (this.t <= 0) return 0;
return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM));
}
// (protected) r = this << n*DB
function bnpDLShiftTo(n, r) {
var i;
for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i];
for (i = n - 1; i >= 0; --i) r[i] = 0;
r.t = this.t + n;
r.s = this.s;
}
// (protected) r = this >> n*DB
function bnpDRShiftTo(n, r) {
for (var i = n; i < this.t; ++i) r[i - n] = this[i];
r.t = Math.max(this.t - n, 0);
r.s = this.s;
}
// (protected) r = this << n
function bnpLShiftTo(n, r) {
var bs = n % this.DB;
var cbs = this.DB - bs;
var bm = (1 << cbs) - 1;
var ds = Math.floor(n / this.DB), c = (this.s << bs) & this.DM, i;
for (i = this.t - 1; i >= 0; --i) {
r[i + ds + 1] = (this[i] >> cbs) | c;
c = (this[i] & bm) << bs;
}
for (i = ds - 1; i >= 0; --i) r[i] = 0;
r[ds] = c;
r.t = this.t + ds + 1;
r.s = this.s;
r.clamp();
}
// (protected) r = this >> n
function bnpRShiftTo(n, r) {
r.s = this.s;
var ds = Math.floor(n / this.DB);
if (ds >= this.t) { r.t = 0; return; }
var bs = n % this.DB;
var cbs = this.DB - bs;
var bm = (1 << bs) - 1;
r[0] = this[ds] >> bs;
for (var i = ds + 1; i < this.t; ++i) {
r[i - ds - 1] |= (this[i] & bm) << cbs;
r[i - ds] = this[i] >> bs;
}
if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs;
r.t = this.t - ds;
r.clamp();
}
// (protected) r = this - a
function bnpSubTo(a, r) {
var i = 0, c = 0, m = Math.min(a.t, this.t);
while (i < m) {
c += this[i] - a[i];
r[i++] = c & this.DM;
c >>= this.DB;
}
if (a.t < this.t) {
c -= a.s;
while (i < this.t) {
c += this[i];
r[i++] = c & this.DM;
c >>= this.DB;
}
c += this.s;
}
else {
c += this.s;
while (i < a.t) {
c -= a[i];
r[i++] = c & this.DM;
c >>= this.DB;
}
c -= a.s;
}
r.s = (c < 0) ? -1 : 0;
if (c < -1) r[i++] = this.DV + c;
else if (c > 0) r[i++] = c;
r.t = i;
r.clamp();
}
// (protected) r = this * a, r != this,a (HAC 14.12)
// "this" should be the larger one if appropriate.
function bnpMultiplyTo(a, r) {
var x = this.abs(), y = a.abs();
var i = x.t;
r.t = i + y.t;
while (--i >= 0) r[i] = 0;
for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t);
r.s = 0;
r.clamp();
if (this.s != a.s) BigInteger.ZERO.subTo(r, r);
}
// (protected) r = this^2, r != this (HAC 14.16)
function bnpSquareTo(r) {
var x = this.abs();
var i = r.t = 2 * x.t;
while (--i >= 0) r[i] = 0;
for (i = 0; i < x.t - 1; ++i) {
var c = x.am(i, x[i], r, 2 * i, 0, 1);
if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
r[i + x.t] -= x.DV;
r[i + x.t + 1] = 1;
}
}
if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1);
r.s = 0;
r.clamp();
}
// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
// r != q, this != m.  q or r may be null.
function bnpDivRemTo(m, q, r) {
var pm = m.abs();
if (pm.t <= 0) return;
var pt = this.abs();
if (pt.t < pm.t) {
if (q != null) q.fromInt(0);
if (r != null) this.copyTo(r);
return;
}
if (r == null) r = nbi();
var y = nbi(), ts = this.s, ms = m.s;
var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus
if (nsh > 0) { pm.lShiftTo(nsh, y); pt.lShiftTo(nsh, r); }
else { pm.copyTo(y); pt.copyTo(r); }
var ys = y.t;
var y0 = y[ys - 1];
if (y0 == 0) return;
var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0);
var d1 = this.FV / yt, d2 = (1 << this.F1) / yt, e = 1 << this.F2;
var i = r.t, j = i - ys, t = (q == null) ? nbi() : q;
y.dlShiftTo(j, t);
if (r.compareTo(t) >= 0) {
r[r.t++] = 1;
r.subTo(t, r);
}
BigInteger.ONE.dlShiftTo(ys, t);
t.subTo(y, y); // "negative" y so we can replace sub with am later
while (y.t < ys) y[y.t++] = 0;
while (--j >= 0) {
// Estimate quotient digit
var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2);
if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) {	// Try it out
y.dlShiftTo(j, t);
r.subTo(t, r);
while (r[i] < --qd) r.subTo(t, r);
}
}
if (q != null) {
r.drShiftTo(ys, q);
if (ts != ms) BigInteger.ZERO.subTo(q, q);
}
r.t = ys;
r.clamp();
if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder
if (ts < 0) BigInteger.ZERO.subTo(r, r);
}
// (public) this mod a
function bnMod(a) {
var r = nbi();
this.abs().divRemTo(a, null, r);
if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r);
return r;
}
// Modular reduction using "classic" algorithm
function Classic(m) { this.m = m; }
function cConvert(x) {
if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);
else return x;
}
function cRevert(x) { return x; }
function cReduce(x) { x.divRemTo(this.m, null, x); }
function cMulTo(x, y, r) { x.multiplyTo(y, r); this.reduce(r); }
function cSqrTo(x, r) { x.squareTo(r); this.reduce(r); }
Classic.prototype.convert = cConvert;
Classic.prototype.revert = cRevert;
Classic.prototype.reduce = cReduce;
Classic.prototype.mulTo = cMulTo;
Classic.prototype.sqrTo = cSqrTo;
// (protected) return "-1/this % 2^DB"; useful for Mont. reduction
// justification:
//         xy == 1 (mod m)
//         xy =  1+km
//   xy(2-xy) = (1+km)(1-km)
// x[y(2-xy)] = 1-k^2m^2
// x[y(2-xy)] == 1 (mod m^2)
// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
// JS multiply "overflows" differently from C/C++, so care is needed here.
function bnpInvDigit() {
if (this.t < 1) return 0;
var x = this[0];
if ((x & 1) == 0) return 0;
var y = x & 3; 	// y == 1/x mod 2^2
y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4
y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8
y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16
// last step - calculate inverse mod DV directly;
// assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
y = (y * (2 - x * y % this.DV)) % this.DV; 	// y == 1/x mod 2^dbits
// we really want the negative inverse, and -DV < y < DV
return (y > 0) ? this.DV - y : -y;
}
// Montgomery reduction
function Montgomery(m) {
this.m = m;
this.mp = m.invDigit();
this.mpl = this.mp & 0x7fff;
this.mph = this.mp >> 15;
this.um = (1 << (m.DB - 15)) - 1;
this.mt2 = 2 * m.t;
}
// xR mod m
function montConvert(x) {
var r = nbi();
x.abs().dlShiftTo(this.m.t, r);
r.divRemTo(this.m, null, r);
if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r);
return r;
}
// x/R mod m
function montRevert(x) {
var r = nbi();
x.copyTo(r);
this.reduce(r);
return r;
}
// x = x/R mod m (HAC 14.32)
function montReduce(x) {
while (x.t <= this.mt2)	// pad x so am has enough room later
x[x.t++] = 0;
for (var i = 0; i < this.m.t; ++i) {
// faster way of calculating u0 = x[i]*mp mod DV
var j = x[i] & 0x7fff;
var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM;
// use am to combine the multiply-shift-add into one call
j = i + this.m.t;
x[j] += this.m.am(0, u0, x, i, 0, this.m.t);
// propagate carry
while (x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; }
}
x.clamp();
x.drShiftTo(this.m.t, x);
if (x.compareTo(this.m) >= 0) x.subTo(this.m, x);
}
// r = "x^2/R mod m"; x != r
function montSqrTo(x, r) { x.squareTo(r); this.reduce(r); }
// r = "xy/R mod m"; x,y != r
function montMulTo(x, y, r) { x.multiplyTo(y, r); this.reduce(r); }
Montgomery.prototype.convert = montConvert;
Montgomery.prototype.revert = montRevert;
Montgomery.prototype.reduce = montReduce;
Montgomery.prototype.mulTo = montMulTo;
Montgomery.prototype.sqrTo = montSqrTo;
// (protected) true iff this is even
function bnpIsEven() { return ((this.t > 0) ? (this[0] & 1) : this.s) == 0; }
// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
function bnpExp(e, z) {
if (e > 0xffffffff || e < 1) return BigInteger.ONE;
var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e) - 1;
g.copyTo(r);
while (--i >= 0) {
z.sqrTo(r, r2);
if ((e & (1 << i)) > 0) z.mulTo(r2, g, r);
else { var t = r; r = r2; r2 = t; }
}
return z.revert(r);
}
// (public) this^e % m, 0 <= e < 2^32
function bnModPowInt(e, m) {
var z;
if (e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);
return this.exp(e, z);
}
// protected
BigInteger.prototype.copyTo = bnpCopyTo;
BigInteger.prototype.fromInt = bnpFromInt;
BigInteger.prototype.fromString = bnpFromString;
BigInteger.prototype.clamp = bnpClamp;
BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
BigInteger.prototype.drShiftTo = bnpDRShiftTo;
BigInteger.prototype.lShiftTo = bnpLShiftTo;
BigInteger.prototype.rShiftTo = bnpRShiftTo;
BigInteger.prototype.subTo = bnpSubTo;
BigInteger.prototype.multiplyTo = bnpMultiplyTo;
BigInteger.prototype.squareTo = bnpSquareTo;
BigInteger.prototype.divRemTo = bnpDivRemTo;
BigInteger.prototype.invDigit = bnpInvDigit;
BigInteger.prototype.isEven = bnpIsEven;
BigInteger.prototype.exp = bnpExp;
// public
BigInteger.prototype.toString = bnToString;
BigInteger.prototype.negate = bnNegate;
BigInteger.prototype.abs = bnAbs;
BigInteger.prototype.compareTo = bnCompareTo;
BigInteger.prototype.bitLength = bnBitLength;
BigInteger.prototype.mod = bnMod;
BigInteger.prototype.modPowInt = bnModPowInt;
// "constants"
BigInteger.ZERO = nbv(0);
BigInteger.ONE = nbv(1);
// prng4.js - uses Arcfour as a PRNG
function Arcfour() {
this.i = 0;
this.j = 0;
this.S = new Array();
}
// Initialize arcfour context from key, an array of ints, each from [0..255]
function ARC4init(key) {
var i, j, t;
for (i = 0; i < 256; ++i)
this.S[i] = i;
j = 0;
for (i = 0; i < 256; ++i) {
j = (j + this.S[i] + key[i % key.length]) & 255;
t = this.S[i];
this.S[i] = this.S[j];
this.S[j] = t;
}
this.i = 0;
this.j = 0;
}
function ARC4next() {
var t;
this.i = (this.i + 1) & 255;
this.j = (this.j + this.S[this.i]) & 255;
t = this.S[this.i];
this.S[this.i] = this.S[this.j];
this.S[this.j] = t;
return this.S[(t + this.S[this.i]) & 255];
}
Arcfour.prototype.init = ARC4init;
Arcfour.prototype.next = ARC4next;
// Plug in your RNG constructor here
function prng_newstate() {
return new Arcfour();
}
// Pool size must be a multiple of 4 and greater than 32.
// An array of bytes the size of the pool will be passed to init()
var rng_psize = 256;
// Random number generator - requires a PRNG backend, e.g. prng4.js
// For best results, put code like
// <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'>
// in your main HTML document.
var rng_state;
var rng_pool;
var rng_pptr;
// Mix in a 32-bit integer into the pool
function rng_seed_int(x) {
rng_pool[rng_pptr++] ^= x & 255;
rng_pool[rng_pptr++] ^= (x >> 8) & 255;
rng_pool[rng_pptr++] ^= (x >> 16) & 255;
rng_pool[rng_pptr++] ^= (x >> 24) & 255;
if (rng_pptr >= rng_psize) rng_pptr -= rng_psize;
}
// Mix in the current time (w/milliseconds) into the pool
function rng_seed_time() {
rng_seed_int(new Date().getTime());
}
// Initialize the pool with junk if needed.
if (rng_pool == null) {
rng_pool = new Array();
rng_pptr = 0;
var t;
if (navigator.appName == "Netscape" && navigator.appVersion < "5" && window.crypto) {
// Extract entropy (256 bits) from NS4 RNG if available
var z = window.crypto.random(32);
for (t = 0; t < z.length; ++t)
rng_pool[rng_pptr++] = z.charCodeAt(t) & 255;
}
while (rng_pptr < rng_psize) {  // extract some randomness from Math.random()
t = Math.floor(65536 * Math.random());
rng_pool[rng_pptr++] = t >>> 8;
rng_pool[rng_pptr++] = t & 255;
}
rng_pptr = 0;
rng_seed_time();
//rng_seed_int(window.screenX);
//rng_seed_int(window.screenY);
}
function rng_get_byte() {
if (rng_state == null) {
rng_seed_time();
rng_state = prng_newstate();
rng_state.init(rng_pool);
for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr)
rng_pool[rng_pptr] = 0;
rng_pptr = 0;
//rng_pool = null;
}
// TODO: allow reseeding after first request
return rng_state.next();
}
function rng_get_bytes(ba) {
var i;
for (i = 0; i < ba.length; ++i) ba[i] = rng_get_byte();
}
function SecureRandom() { }
SecureRandom.prototype.nextBytes = rng_get_bytes;
// Depends on jsbn.js and rng.js
// Version 1.1: support utf-8 encoding in pkcs1pad2
// convert a (hex) string to a bignum object
function parseBigInt(str, r) {
return new BigInteger(str, r);
}
function linebrk(s, n) {
var ret = "";
var i = 0;
while (i + n < s.length) {
ret += s.substring(i, i + n) + "\n";
i += n;
}
return ret + s.substring(i, s.length);
}
function byte2Hex(b) {
if (b < 0x10)
return "0" + b.toString(16);
else
return b.toString(16);
}
// PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
function pkcs1pad2(s, n) {
if (n < s.length + 11) { // TODO: fix for utf-8
alert("Message too long for RSA");
return null;
}
var ba = new Array();
var i = s.length - 1;
while (i >= 0 && n > 0) {
var c = s.charCodeAt(i--);
if (c < 128) { // encode using utf-8
ba[--n] = c;
}
else if ((c > 127) && (c < 2048)) {
ba[--n] = (c & 63) | 128;
ba[--n] = (c >> 6) | 192;
}
else {
ba[--n] = (c & 63) | 128;
ba[--n] = ((c >> 6) & 63) | 128;
ba[--n] = (c >> 12) | 224;
}
}
ba[--n] = 0;
var rng = new SecureRandom();
var x = new Array();
while (n > 2) { // random non-zero pad
x[0] = 0;
while (x[0] == 0) rng.nextBytes(x);
ba[--n] = x[0];
}
ba[--n] = 2;
ba[--n] = 0;
return new BigInteger(ba);
}
// "empty" RSA key constructor
function RSAKey() {
this.n = null;
this.e = 0;
this.d = null;
this.p = null;
this.q = null;
this.dmp1 = null;
this.dmq1 = null;
this.coeff = null;
}
// Set the public key fields N and e from hex strings
function RSASetPublic(N, E) {
if (N != null && E != null && N.length > 0 && E.length > 0) {
this.n = parseBigInt(N, 16);
this.e = parseInt(E, 16);
}
else
alert("Invalid RSA public key");
}
// Perform raw public operation on "x": return x^e (mod n)
function RSADoPublic(x) {
return x.modPowInt(this.e, this.n);
}
// Return the PKCS#1 RSA encryption of "text" as an even-length hex string
function RSAEncrypt(text) {
var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3);
if (m == null) return null;
var c = this.doPublic(m);
if (c == null) return null;
var h = c.toString(16);
if ((h.length & 1) == 0) return h; else return "0" + h;
}
// Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string
//function RSAEncryptB64(text) {
//  var h = this.encrypt(text);
//  if(h) return hex2b64(h); else return null;
//}
// protected
RSAKey.prototype.doPublic = RSADoPublic;
// public
RSAKey.prototype.setPublic = RSASetPublic;
RSAKey.prototype.encrypt = RSAEncrypt;
//RSAKey.prototype.encrypt_b64 = RSAEncryptB64;
RJS.RSAKey = RSAKey;
})();

/*************************** rjs.errors.js ***************************/
if (typeof RJS === 'undefined') window.RJS = {};
RJS.Errors = new function() {
var self = this;
var state = {};
var $ = jQuery;
function LoadError(src, msg) {
if ($('.rjsError').length > 0) {
var err = $('.rjsError').filter(function() {
return $(this).parent().filter(':visible').length > 0;
});
err.removeClass('success');
err.slideDown('fast');
var previousHtml = err.html().trim();
if (previousHtml.length !== 0) {
previousHtml += "<br />";
}
err.html(previousHtml + msg);
$('html, body').animate({ scrollTop: 0 /*err.offset().top*/ }, "fast");
} else {
window.console && console.log('No error container. Error: { src: "', src, '", msg: "', msg, '" }');
}
}
self.show = function(src, msg, details) {
try {
state[src] = msg;
var prm = Sys.WebForms.PageRequestManager.getInstance();
var isInAsyncPostback = prm.get_isInAsyncPostBack();
function ShowError() {
LoadError(src, msg);
prm.remove_endRequest(ShowError);
}
if (isInAsyncPostback) {
prm.add_endRequest(ShowError);
} else {
$(document).ready(function() {
LoadError(src, msg);
});
}
} catch (err) { if (window.console) console.log("", err); }
if (details && window.console) {
if (console.error) { console.error(details); }
else { console.log(details); }
}
};
self.success = function(src, msg) {
try {
if ($('.rjsError').length > 0) {
var err = $('.rjsError').filter(function() {
return $(this).parent().filter(':visible').length > 0;
});
err.slideDown('fast');
err.addClass('success');
err.html(msg);
$('html, body').animate({ scrollTop: 0 /*err.offset().top*/ }, "fast");
}
} catch (err) { if (window.console) console.log("", err); }
}
self.clear = function(src) {
delete state[src];
$('.rjsError').hide();
};
};
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(sender, e) {
var err = e.get_error();
if (err) {
if (err.name === "Sys.WebForms.PageRequestManagerTimeoutException") {
RJS.Errors.show("up", "The server took longer than expected to respond. Please try again.");
} else if (err.name === "Sys.WebForms.PageRequestManagerServerErrorException" && err.message.indexOf("The status code returned from the server was: 404") != -1) {
RJS.Errors.show("up", "The server could not handle your request (404 Error). Please reload the page and try again.");
} else if (err.name === "Sys.WebForms.PageRequestManagerServerErrorException" && err.message.indexOf("Failed to load viewstate.") !== -1) {
window.location.reload();
} else {
RJS.Errors.show("up", err.message);
}
e.set_errorHandled(true);
}
});

/*************************** rjs.jq.js ***************************/
FilterSpecialChars = function() {
var except = [];
var handler = function(evt) {
switch (evt.charCode || evt.keyCode) {
case 60:
case 62:
case 42:
return false;
default:
return true;
}
};
var allowHtml = function(e) {
except.push(e);
jQuery(e).unbind("keypress", handler);
};
jQuery("input[type=text]").keypress(handler);
return { allowHtml: allowHtml };
}();
(function($) {
var prm = Sys.WebForms.PageRequestManager.getInstance();
var buttonsToDisable = $("");
var linksToDisable = $("");
function cancelAsyncPostback(sender, args) {
args.set_cancel(true);
window.console && console.log('cancelled postback!');
}
prm.add_beginRequest(function(sender, args) {
//if (!RJS.allowDoubleFormSubmissions) {
buttonsToDisable = $("button, input[type=submit], input[type=button]").filter(function() { return !$(this).attr('disabled'); });
linksToDisable = $("a[href^='javascript:']");
buttonsToDisable.attr('disabled', 'disabled');
linksToDisable.each(function() {
var $this = $(this);
$this.data('original-href', $this.attr('href'));
$this.attr('href', 'javascript:');
});
prm.add_initializeRequest(cancelAsyncPostback);
//}
$(".Loading, .LoadingUnderlay").show();
});
prm.add_endRequest(function(sender, args) {
//if (!RJS.allowDoubleFormSubmissions) {
buttonsToDisable.removeAttr('disabled', 'disabled');
linksToDisable.each(function() {
var $this = $(this);
$this.attr('href', $this.data('original-href'));
});
buttonsToDisable = $("");
linksToDisable = $("");
prm.remove_initializeRequest(cancelAsyncPostback);
//}
$(".Loading, .LoadingUnderlay").hide();
});
})(jQuery);

/*************************** rjs.jq.spots.js ***************************/
jQuery(document).ready(function($) {
// Misc - Advanced Selector replacement for tabs (css for this doesn't work in IE7)
//***************************
function removeBorder() {
var divs = $('#mw ol.hottest li:first, #rp ol.hottest li:first, #lc ol.hottest li:first, #picks ol.hottest li:first, div.toolbarWrap div:first, div.channelInner ul li:odd');
divs.addClass('noborder');
}
function addFirst() {
var first = $('ul.tabs li:first, ol.whatsHot li:first');
first.addClass('first');
}
function addLast() {
var last = $('ul.tabs li:last-child, ul.floatList li:last');
last.addClass('last');
}
// Run Functions
removeBorder();
addFirst()
addLast()
$('ul.links li:last').addClass('noMarginBottom');
$("ul.tabs li:only-child").addClass('solo').removeClass('first').removeClass('last');
//***************************
// End
// Main Menu Docks
//***************************
function loadDocks() {
var header = $("#headerWrap");
if (header.length === 0) return;
$.get(URLUtil.resolveUrl("~/d/" + $("#DataVersion").val() + "/navdocks"), function(html) {
var navDocks = $(html);
$("#moviesDock").html(navDocks.children(".movies").html());
$("#tvDock").html(navDocks.children(".tv").html());
$("#clipsDock").html(navDocks.children(".clips").html());
$("#storeDock").html(navDocks.children(".store").html());
});
}
$(window).load(loadDocks);// Defer loading docks until after visible page content is finished loading.
var hoverIntentTime = 200;
var menuItems = $(".menu > li.hasDropDown");
var anchorDocks = $("#NavDocks").children("a.hasDropDown");
var contentDocks = $("#NavDocks").children("div");
var selectWraps = $("select");
selectWraps.each(function() {
try {
var $this = $(this);
if (!$this.next().is(".dropDownPlaceholder")) {
var dropDownPlaceHolder = $('<div class="dropDownPlaceholder"></div>');
dropDownPlaceHolder.css({// Make the placeholder have the EXACT same dimensions & layout styles as the original drop down
width: $this.innerWidth(),
height: $this.innerHeight(),
borderTopStyle: $this.css("border-top-style"),
borderBottomStyle: $this.css("border-bottom-style"),
borderLeftStyle: $this.css("border-left-style"),
borderRightStyle: $this.css("border-right-style"),
borderTopWidth: $this.css("border-top-width"),
borderBottomWidth: $this.css("border-bottom-width"),
borderLeftWidth: $this.css("border-left-width"),
borderRightWidth: $this.css("border-right-width"),
paddingTop: $this.css("padding-top"),
paddingBottom: $this.css("padding-bottom"),
paddingLeft: $this.css("padding-left"),
paddingRight: $this.css("padding-right"),
marginTop: $this.css("margin-top"),
marginBottom: $this.css("margin-bottom"),
marginLeft: $this.css("margin-left"),
marginRight: $this.css("margin-right"),
visibility: "hidden",
"float": $this.css("float")
});
$this.after(dropDownPlaceHolder);
}
$this.next().hide();
} catch (ex) {
if (window.console) {
if (console.error) console.error(ex);
else console.log(JSON.stringify(ex));
}
}
});
function showNavTray() {
RJS.Tooltip.hideAll();
var index = menuItems.index(this);
var currentTab = anchorDocks.eq(index).show();
var currentContent = contentDocks.eq(index).show();
anchorDocks.not(currentTab).hide();
contentDocks.not(currentContent).hide();
if (currentContent.children().length > 0) {
selectWraps.hide();
selectWraps.next().show();
setTimeout(function() { selectWraps.show().next().hide(); }, 1);
}
RJS.Timer.clear('hide', 'hide');
return false;
}
function hideNavTray(ev) {
if (ev) {// IE7 will trigger mouseover events even if the mouse is over the nav tray. Check the event target to make sure the menu REALLY should be hidden
var $target = $(ev.target);
if ($target.closest('#NavDocks').length > 0) return true;
var index = anchorDocks.index($target.closest('a'));
if (index > -1) return true;
index = menuItems.index($target.closest('li'));
if (index > -1) return true;
index = contentDocks.index($target.closest('.navWrap'));
if (index > -1) return true;
}
anchorDocks.hide();
contentDocks.hide();
RJS.Timer.clear('hide', 'hide');
}
menuItems.hover(function() {
var self = this;
RJS.Timer.add('show', self.id, function() {
showNavTray.apply(self);
RJS.Timer.clear('show', self.id);
}, hoverIntentTime);
return false;
}, function() {
var self = this;
RJS.Timer.clear('show', self.id);
});
anchorDocks.add(contentDocks).mouseover(function() {
RJS.Timer.clear('hide', 'hide');
return false;
});
$(document).click(hideNavTray);
$(document.body).mouseover(function() {
var jThis = this, jArgs = arguments;
RJS.Timer.add('hide', 'hide', function() { hideNavTray.apply(jThis, jArgs) }, hoverIntentTime);
});
//***************************
// End
});
jQuery(function() {
// Add no border to first div
//***************************
jQuery(".tabbed_box .tabs li a").click(function() {
jQuery('div.toolbarWrap div:first').addClass('noborder'); return false;
});
//***************************
// End
// Add active states to util links
//***************************
jQuery('#navigation ul li a').click(function() { //When any link is clicked
jQuery(this).removeClass('active'); // Remove active class from all links
jQuery(this).parent().addClass('active'); //Set clicked link class to active
});
//***************************
// End
});
jQuery(document).ready(function() {
//Animate Anchor Link - Back To Top
//***************************
jQuery.fn.anchorAnimate = function(settings) {
settings = jQuery.extend({
speed: 200
}, settings);
return this.each(function() {
var caller = this
jQuery(caller).click(function(event) {
event.preventDefault()
var locationHref = window.location.href
var elementClick = jQuery(caller).attr("href")
var destination = jQuery(elementClick).offset().top;
jQuery("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination }, settings.speed, function() {
window.location.hash = elementClick
});
return false;
})
})
}
//    function print_ie() {
//        if (!jQuery.support.cssFloat) {
//            jQuery(window)
//            .bind('beforeprint', function() {
//                jQuery('img.DD_roundies_sizeFinder,ignore,shape,fill').hide();
//                jQuery('img.DD_roundies_sizeFinder')
//                    .attr('src', './i/b.gif')
//                    .css({ width: '1px', height: '1px' });
//            })
//            .bind('afterprint', function() {
//                jQuery('img.DD_roundies_sizeFinder,ignore,shape,fill').show();
//            });
//        }
//    }
//    print_ie();
jQuery("a.anchorLink").anchorAnimate()
//***************************
// End
});
//jQuery(window).load(function() {
//DD_roundies.addRule('.contentWrap', '0 5px 5px 5px', true);
//DD_roundies.addRule('.contentWrap.wrapAll, table.wrapAll, .textWrap, .new-btn, .round-button', '5px 5px 5px 5px', true);
//DD_roundies.addRule('.contentWrap.search, .contentWrap.genres, .contentWrap.wrapAll, table.wrapAll, .textWrap', '5px 5px 5px 5px', true);
//DD_roundies.addRule('.navWrap', '2px 2px 2px 2px', true);
//DD_roundies.addRule('li.solo a', '3px 3px 0 0', true);
//DD_roundies.addRule('.roundAll', '3px 3px 3px 3px', true);
//});

/*************************** rjs.jq.tabs.js ***************************/
(function rjsTabs($) {
/////////////////////////////////////////
// Public Methods:
/////////////////////////////////////////
// RJS.Tabs.tabFocused([id], handler);
//    ID is optional. If specified, handler will only be called if the ID specified is contained within the tab being switched to. You shouldn't need ID in most cases.
//
// RJS.Tabs.activateTab(tabBox, tabIndex)
//    tabBox:   Element that matches the CSS Selector: div.tabbed_box
//    tabIndex: 0-based index of the tab to activate
//
// RJS.Tabs.getActiveTabIndex(tabBox)
//    tabBox: Element that matches the CSS Selector: div.tabbed_box
var tabEventListeners = { generalListeners: [], specificlisteners: {} };
function activateTab(tabBox, index) {
$(".toolbarWrap div:first-child").addClass("noborder");
var theTab = tabBox.find(".tabs li a").removeClass("active").eq(index).addClass("active");
var theContent = tabBox.children().children(".contentWrap").children(".content").hide().eq(index).show();
// Trigger tabFocused events
for (var id in tabEventListeners.specificlisteners) {
if (theContent.find("#" + id).length > 0) {
for (var i = 0; i < tabEventListeners.specificlisteners[id].length; i++) {
tabEventListeners.specificlisteners[id][i](tabBox, theTab, theContent);
}
}
}
for (var i = 0; i < tabEventListeners.generalListeners.length; i++) {
tabEventListeners.generalListeners[i](tabBox, theTab, theContent);
}
}
function getActiveTabIndex(tabBox) {
var tabs = tabBox.find(".tabs li a");
var index = tabs.index(tabs.filter(".active").get(0));
if (index > -1) return index;
var contents = tabBox.find("div.contentWrap .content");
index = contents.index(":visible");
return index;
}
if (typeof RJS === 'undefined') window.RJS = {};
RJS.Tabs = {};
RJS.Tabs.activateTab = activateTab;
RJS.Tabs.getActiveTabIndex = getActiveTabIndex;
RJS.Tabs.init = init;
// id is optional and may be ommitted. If id is included, the handler
// is only called if the tab being focused contains the specified ID
RJS.Tabs.tabFocused = function (id, handler) {
if (handler === undefined && arguments.length === 1 && typeof id === "function") {
tabEventListeners.generalListeners.push(id);
return;
}
if (tabEventListeners.specificlisteners[id] === undefined) {
tabEventListeners.specificlisteners[id] = [];
}
tabEventListeners.specificlisteners[id].push(handler);
};
var tabBoxes = null;
var allTabs = null;
var sideLinks = null;
function setTab(tabBox, tab) {
var index = tabBox.find(".tabs a").index(tab);
if (index != -1) {
sideLinks.removeClass("active")
.filter("a[rel='" + tab.attr("rel") + "']")
.addClass("active");
activateTab(tabBox, index);
}
}
function findAndSetTab(rel) {
var tab = allTabs.find("a[rel='" + rel + "']");
if (tab.length === 1) {
var tabBox = tab.closest(".tabbed_box");
setTab(tabBox, tab);
return true;
} else {
return false;
}
}
$(function () {
var header = $("#headerWrap");
$(".navWrap li a[rel]", header).live("click.rjsTabs", function (ev) {
// Only intercept the nav clicks if they are links to the current page, otherwise let the browser direct the user
var href = this.href.replace(new RegExp("#.*", "ig"), "");
var loc = window.location.toString().replace(new RegExp("#.*", "ig"), "");
var regex = new RegExp(href + "$", "ig");
if (regex.test(loc)) {
if (findAndSetTab(this.rel)) {
ev.preventDefault();
return false;
}
}
});
init();
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(init);
});
function init() {
// Prefetch tabs & tab boxes to speed up access to them when the user clicks a tab
tabBoxes = $("div.tabbed_box");
allTabs = tabBoxes.find("ul.tabs");
sideLinks = $("#two-col .section .links a[rel]");
var locationHash = location.hash;
allTabs.find("li a").unbind("click.rjsTabs").bind("click.rjsTabs", function (ev) {
if (tabBoxes.length > 1) {
var tabBox = $(this).closest(".tabbed_box");
} else {
var tabBox = tabBoxes.eq(0);
}
setTab(tabBox, $(this));
ev.preventDefault();
});
sideLinks.unbind("click.rjsTabs").bind("click.rjsTabs", function (ev) {
if (findAndSetTab(this.rel)) {
ev.preventDefault();
return false;
}
});
tabBoxes.each(function () {
$this = $(this);
setTab($this, $this.find(".tabs a:eq(0)"));
});
if (locationHash) {
var hash = locationHash.gsub("#_", "").gsub("#", "");
findAndSetTab(hash);
}
}
})(jQuery);

/*************************** rjs.jtooltip.js ***************************/
(function ($, window) {
var loggingEnabled = false;
function log() {
try {
if (loggingEnabled && window.console) {
if (typeof console != 'undefined' && typeof console.log == 'function') {
console.log.apply(console, arguments);
} else if (!Function.prototype.bind && typeof console != 'undefined' && typeof console.log == 'object') {
Function.prototype.call.call(console.log, console, Array.prototype.slice.call(arguments));
}
}
} catch (e) { }
}
RJS.typeSequence("debugger", function () {
loggingEnabled = !loggingEnabled;
window.console && console.log('Logging ' + (loggingEnabled ? 'enabled' : 'disabled'));
});
var dataVersionInputField = document.getElementById('DataVersion');
if (dataVersionInputField != null) {
var dataVersion = document.getElementById('DataVersion').value;
} else {
log("DATA VERSION NOT LOADED. BAD THINGS MAY HAPPEN!");
}
var $window = $(window),
$body = $(document.body),
ttCounter = 0;
var jttDefaults = {
showDelayMilliseconds: 500,
hideDelayMilliseconds: 300,
errorMessageResetCooldown: 5000,
replacementSelector: '.elementToReplaceWithContents',
template: jQuery('<div class="asset-hover hide" style="position:absolute"><div class="elementToReplaceWithContents">Loading...</div><div class="pointer"></div></div>'),
contentUrl: function ($elem) {
var id = $elem.parent().data('id');
return URLUtil.resolveUrl('~/d/' + dataVersion + '/tooltip?id=' + id);
},
positionClasses: { topRight: 'ah-r-b', topLeft: 'ah-b', right: 'ah-l', bottomRight: 'ah-t', bottomLeft: 'ah-r-t', left: 'ah-r' },
pointerMargin: { top: 13, right: 13, bottom: 13, left: 13 },
delegateSelector: null//Must be a valid jQuery selector
};
var hideTooltipTimer = null;
var showTooltipTimer = null;
// Intersect box is a debugging tool that is displayed if debugging is enabled to show where the cursor can be positioned between a thumbnail and a tooltip that will allow the tooltip to remain visible.
var intersectBox = $('<div id="intersectbox" style="background:transparent; border:1px solid #0f0; position: absolute; display:none;z-index:999999; box-sizing: border-box"></div>');
$body.append(intersectBox);
var tooltipContainer = $('<div id="tooltip-container"></div>');
$body.append(tooltipContainer); // Add to the document as early as possible, in case a tooltip is generated before page-load is finished
$(window).load(function () { $body.append(tooltipContainer); }); //After the document has finished loading, move the container to the very end of the document to help ensure it will get z-index priority over other elements.
function isNullOrEmpty(guid) {
return typeof guid === 'undefined' && guid == null && guid == '' && guid == "00000000-0000-0000-0000-000000000000";
}
function containsGuid(lockedttContent, user, entitlement, rental) {
if ("rentals" in user && user.rentals.length > 0 && !isNullOrEmpty(rental)) {
for (var i = 0; i < user.rentals.length; i++) {
if (user.rentals[i] === rental) {
lockedttContent.removeClass('unentitled').addClass('entitled');
break;
}
}
}
else if ("entitlements" in user && user.entitlements != null && !isNullOrEmpty(entitlement)) {
for (var i = 0; i < user.entitlements.length; i++) {
if (user.entitlements[i] === entitlement) {
lockedttContent.removeClass('unentitled').addClass('entitled');
break;
}
}
}
}
$(window).load(function () {
RJS.User.add_UserInfoLoaded(applyUserSettingsToTooltips);
});
function hasRental(assetId) {
if (!assetId || !("rentals" in RJS.User) || RJS.User.rentals.length <= 0) {
return false;
}
for (var i = 0; i < RJS.User.rentals.length; i++) {
if (RJS.User.rentals[i] == assetId)
return true;
}
return false;
}
function applyUserSettingsToTooltips() {
var allTooltips = tooltipContainer.find('div.asset-hover-content');
allTooltips.each(function () {
var $tt = $(this),
eid = $tt.data('entitlement'),
aid = $tt.data('id');
if (hasRental(aid)) {
$tt.find('a[href~="/rentals/detail/"]').each(function() {
this.href = this.href.replace('/rentals/detail/', '/rentals/watch/');
});
}
if ($tt.hasClass('unentitled')) {
containsGuid($tt, RJS.User, eid, aid);
}
});
}
$.fn.jTooltip = function (options) {
var $self = this,
o = $.extend({}, jttDefaults, options),
setHideTimer = function ($elem, $tt) {
if (hideTooltipTimer != null) {
clearTimeout(hideTooltipTimer);
}
hideTooltipTimer = setTimeout(hideTooltip($elem, $tt), o.hideDelayMilliseconds);
},
setShowTimer = function ($elem, $tt) {
if (showTooltipTimer != null) {
clearTimeout(showTooltipTimer);
}
showTooltipTimer = setTimeout(showTooltip($elem, $tt), o.showDelayMilliseconds);
},
isPointInBox = function (point, rect) {
return point.x > rect.startX && point.x < rect.stopX && point.y > rect.startY && point.y < rect.stopY;
},
getRectangle = function ($elem) {
var position = $elem.offset();
return { startX: position.left, startY: position.top, stopX: (position.left + $elem.width()), stopY: (position.top + $elem.height()) };
},
hideTooltip = function ($elem, $tt) {
// Calculate whether the tooltip should be hidden by checking if the cursor
// is in 3 possible boxes on the page: the video thumbnail, the tooltip, or
// the open space between the 2 boxes referred to as the "intersection" described in
// P:\Rogers_Cable\Rogers_111_SearchImplementation\IA\Search Update v1.8.pdf page 5, note 4
return function () {
var m = RJS.Mouse,
elemRect = getRectangle($elem),
ttRect = getRectangle($tt),
intersectRect = { startX: 0, startY: 0, stopX: 0, stopY: 0 };
if ($tt.hasClass(o.positionClasses.right)) {
intersectRect.startX = elemRect.stopX - 1;
intersectRect.startY = Math.max(elemRect.startY, ttRect.startY);
intersectRect.stopX = ttRect.startX + 1;
intersectRect.stopY = Math.min(elemRect.stopY, ttRect.stopY);
} else if ($tt.hasClass(o.positionClasses.left)) {
intersectRect.startX = ttRect.stopX - 1;
intersectRect.startY = Math.max(elemRect.startY, ttRect.startY);
intersectRect.stopX = elemRect.startX + 1;
intersectRect.stopY = Math.min(elemRect.stopY, ttRect.stopY);
} else if ($tt.hasClass(o.positionClasses.bottomRight) || $tt.hasClass(o.positionClasses.bottomLeft)) {
intersectRect.startX = Math.max(ttRect.startX, elemRect.startX);
intersectRect.startY = elemRect.stopY - 1;
intersectRect.stopX = Math.min(ttRect.stopX, elemRect.stopX);
intersectRect.stopY = ttRect.startY + 1;
} else if ($tt.hasClass(o.positionClasses.topRight) || $tt.hasClass(o.positionClasses.topLeft)) {
intersectRect.startX = Math.max(ttRect.startX, elemRect.startX);
intersectRect.startY = ttRect.stopY - 1;
intersectRect.stopX = Math.min(ttRect.stopX, elemRect.stopX);
intersectRect.stopY = elemRect.startY + 1;
}
if (loggingEnabled) {
intersectBox.show().css({ top: intersectRect.startY, left: intersectRect.startX, height: intersectRect.stopY - intersectRect.startY, width: intersectRect.stopX - intersectRect.startX });
}
if (isPointInBox(m, elemRect) || isPointInBox(m, ttRect) || isPointInBox(m, intersectRect)) {
setHideTimer($elem, $tt); // If the cursor is in 1 of the 3 boxes, wait and calcuate again in a few milliseconds.
} else {
if (loggingEnabled) {
intersectBox.hide();
}
$tt.removeClass('show').addClass('hide');
}
};
},
showTooltip = function ($elem, $tt) {
return function () {
var elemRect = getRectangle($elem),
m = RJS.Mouse;
if (!isPointInBox(m, elemRect)) {
return;
}
$tt.removeClass('hide').addClass('show');
calculatePosition($elem, $tt);
};
},
mouseenterHandler = function (ev) {
var $elem = $(this),
ttid = $elem.data('jttid'),
$tt;
if (ttid != null) { // Tooltip has already been created for this element
$tt = $('#' + ttid);
tooltipContainer.children('.show').not($tt).removeClass('show').addClass('hide');
setShowTimer($elem, $tt);
} else { // We need to generate a tooltip for this element
var url = o.contentUrl($elem);
$tt = o.template.clone();
$elem.data('jttid', 'jtt-' + ttCounter);
$tt.attr('id', 'jtt-' + ttCounter);
tooltipContainer.append($tt);
ttCounter++;
calculatePosition($elem, $tt);
tooltipContainer.children('.show').not($tt).removeClass('show').addClass('hide');
setShowTimer($elem, $tt);
$.ajax({ url: url, dataType: 'html', success: updateContents($elem, $tt), error: handleContentLoadFailure($elem, $tt) });
}
setHideTimer($elem, $tt);
},
positionRight = function (p, $elem, $tt) {
var ttLeft = p.e.left + p.e.width + o.pointerMargin.right,
ttTop = p.e.top + (p.e.height * 0.30); // top of tooltip should be 30% of the way down the thumbnail
if (ttTop < p.w.top) {// Partially above the top of the viewport
positionBottom(p, $elem, $tt);
} else if ((ttTop + p.tt.height) > (p.w.top + p.w.height)) {// Partially below the bottom of the viewport
ttTop = (p.e.top - p.tt.height) + (p.e.height * 0.70);
if (ttTop < p.w.top) {// If we reach this point, the tooltip has no room either vertically or horizontally. In this case, re-position the tooltip to the original position (lower right) so the top of the tooltip aligns with the top of the thumbnail.
ttTop = p.e.top + (p.e.height * 0.30);
log("Positioning this correctly is hopeless.");
}
}
$tt.css({ left: ttLeft, top: ttTop }).removeClass(o.positionClasses.left + ' ' + o.positionClasses.topLeft + ' ' + o.positionClasses.topRight + ' ' + o.positionClasses.bottomLeft + ' ' + o.positionClasses.bottomRight)
.addClass(o.positionClasses.right);
var pointerTop = (p.e.top + (p.e.height / 2)) - ttTop;
var $pointer = $tt.find('.pointer');
pointerTop -= $pointer.height() / 2;
$pointer.css({ top: pointerTop + 'px', left: '' });
},
positionLeft = function (p, $elem, $tt) {
var ttLeft = p.e.left - p.tt.width - o.pointerMargin.right,
ttTop = p.e.top + (p.e.height * 0.30); // top of tooltip should be 30% of the way down the thumbnail
if (ttTop < p.w.top) {
positionBottom(p, $elem, $tt);
} else if ((ttTop + p.tt.height) > (p.w.top + p.w.height)) {// Partially below the bottom of the viewport
ttTop = (p.e.top - p.tt.height) + (p.e.height * 0.70);
if (ttTop < p.w.top) {// If we reach this point, the tooltip has no room either vertically or horizontally. In this case, re-position the tooltip to the original position (lower left) so the top of the tooltip aligns with the top of the thumbnail.
ttTop = p.e.top + (p.e.height * 0.30);
log("Positioning this correctly is hopeless.");
}
}
$tt.css({ left: ttLeft, top: ttTop }).removeClass(o.positionClasses.right + ' ' + o.positionClasses.topLeft + ' ' + o.positionClasses.topRight + ' ' + o.positionClasses.bottomLeft + ' ' + o.positionClasses.bottomRight)
.addClass(o.positionClasses.left);
var pointerTop = (p.e.top + (p.e.height / 2)) - ttTop;
var $pointer = $tt.find('.pointer');
pointerTop -= $pointer.height() / 2;
$pointer.css({ top: pointerTop + 'px', left: '' });
},
positionBottom = function (p, $elem, $tt) {
var ttLeft = p.e.left + (p.e.width * 0.30),
ttTop = p.e.top + p.e.height + o.pointerMargin.bottom;
if ((ttLeft + p.tt.width) > (p.w.left + p.w.width)) {
ttLeft = (p.e.left - p.tt.width) + (p.e.width * 0.70);
$tt.css({ left: ttLeft, top: ttTop }).removeClass(o.positionClasses.left + ' ' + o.positionClasses.right + ' ' + o.positionClasses.topLeft + ' ' + o.positionClasses.topRight + ' ' + o.positionClasses.bottomRight)
.addClass(o.positionClasses.bottomLeft);
} else {
$tt.css({ left: ttLeft, top: ttTop }).removeClass(o.positionClasses.left + ' ' + o.positionClasses.right + ' ' + o.positionClasses.topLeft + ' ' + o.positionClasses.topRight + ' ' + o.positionClasses.bottomLeft)
.addClass(o.positionClasses.bottomRight);
}
var pointerLeft = (p.e.left + (p.e.width / 2)) - ttLeft;
var $pointer = $tt.find('.pointer');
pointerLeft -= $pointer.height() / 2;
$pointer.css({ left: pointerLeft + 'px', top: '' });
},
positionTop = function (p, $elem, $tt) {
var ttLeft = p.e.left + (p.e.width * 0.30),
ttTop = p.e.top - o.pointerMargin.top - p.tt.height;
if ((ttLeft + p.tt.width) > (p.w.left + p.w.width)) {
ttLeft = (p.e.left - p.tt.width) + (p.e.width * 0.70);
$tt.css({ left: ttLeft, top: ttTop }).removeClass(o.positionClasses.left + ' ' + o.positionClasses.right + ' ' + o.positionClasses.topRight + ' ' + o.positionClasses.bottomLeft + ' ' + o.positionClasses.bottomRight)
.addClass(o.positionClasses.topLeft);
} else {
$tt.css({ left: ttLeft, top: ttTop }).removeClass(o.positionClasses.left + ' ' + o.positionClasses.right + ' ' + o.positionClasses.topLeft + ' ' + o.positionClasses.bottomRight + ' ' + o.positionClasses.bottomLeft)
.addClass(o.positionClasses.topRight);
}
var pointerLeft = (p.e.left + (p.e.width / 2)) - ttLeft;
var $pointer = $tt.find('.pointer');
pointerLeft -= $pointer.height() / 2;
$pointer.css({ left: pointerLeft + 'px', top: '' });
},
calculatePosition = function ($elem, $tt) {
var eOffset = $elem.offset(),
ttOffset = $tt.offset(),
p = {
e: { top: eOffset.top, left: eOffset.left, height: $elem.height(), width: $elem.width() },
tt: { top: ttOffset.top, left: ttOffset.left, height: $tt.height(), width: $tt.width() },
w: { top: $window.scrollTop(), left: $window.scrollLeft(), height: $window.height(), width: $window.width() }
};
if ((p.e.top + (p.e.height * 0.70)) > (p.w.top + p.w.height)) {
positionTop(p, $elem, $tt);
} else if ((p.e.top + (p.e.height * 0.30)) < p.w.top) {
positionBottom(p, $elem, $tt);
} else if ((p.e.left + p.e.width + p.tt.width + o.pointerMargin.left) < (p.w.width + p.w.left)) { // Check that there is space to place the tooltip to the right of the element
positionRight(p, $elem, $tt);
} else {
positionLeft(p, $elem, $tt);
}
},
updateContents = function ($elem, $tt) {
return function (data, textStatus, jqXhr) {
$tt.find(o.replacementSelector).replaceWith(data);
applyUserSettingsToTooltips();
calculatePosition($elem, $tt);
};
},
handleContentLoadFailure = function ($elem, $tt) {
return function (jqXhr, textStatus, errorThrown) {
log('Error loading content: ', jqXhr, textStatus, errorThrown);
$tt.find(o.replacementSelector).replaceWith("An error occurred attempting to load data for this item. Please try again later.");
setTimeout(function () {
$tt.remove();
$elem.removeData('jttid');
}, o.errorMessageResetCooldown);
};
};
if (o.delegateSelector) {
$self.on('mouseenter', o.delegateSelector, mouseenterHandler);
} else {
$self.on('mouseenter', mouseenterHandler);
}
return $self;
};
})(jQuery, window);

/*************************** rjs.player.js ***************************/
RJS.FlashPlayer = {
open: function(assetID, trailerID) {
window.console && console.log('Called RJS.Player.open(...)');
jQuery("#ajaxPlayerWrapper,#ajaxPlayerOverlay").remove();
function hideOverlay() {
jQuery("#ajaxPlayerWrapper,#ajaxPlayerOverlay").hide();
jQuery("#hero").css("display", "block");
var flashObject = document.getElementById('playerwidget');
if ("stop" in flashObject) {
flashObject.stop();
}
}
jQuery.ajax({
url: URLUtil.resolveUrl("~/h/aspottrailer/" + assetID + "/" + trailerID),
dataType: "html",
success: function(html) {
jQuery("#ajaxPlayerWrapper").remove();
jQuery("#ajaxPlayerOverlay").remove();
var overlay = jQuery('<div id="ajaxPlayerOverlay"></div>').click(hideOverlay);
jQuery("body").prepend(overlay).prepend('<div id="ajaxPlayerWrapper">' + html + "</div>");
jQuery(".ajaxPlayer-close").click(hideOverlay);
jQuery("#hero").css("display", "none");
RJS.Event.bind('flashShowOverlay', function() {
hideOverlay();
RJS.Event.unbind('flashShowOverlay', arguments.callee);
return false;
});
},
error: function() {
window.console && console.log("Error!: ", arguments);
}
});
},
load: function(aid, element, callback) {
jQuery.ajax({
url: URLUtil.resolveUrl("~/h/player/" + aid + ".html"),
dataType: "html",
success: function(html) {
$(element).append(html);
if (callback) callback();
},
error: function() {
window.console && console.log("Error!: ", arguments);
}
});
}
};
jQuery.extend(RJS.Player, RJS.FlashPlayer);

/*************************** rjs.range.js ***************************/
RJS.Range = function(ele, data, options) {
options = Object.extend({
id: "range",
max: 7,
templates: { itemTemplate: jQuery.createTemplate('<span class="slider">{$T}</span>') }
}, options);
if (!(ele = $(ele))) throw ("RJS.Range element not found");
//if (typeof options.url == "undefined") throw ('RJS.Range url is null, must be set to the handler that gives suggestions');
var builder = RJS.Repeater({ templates: options.templates });
ele.update(builder.buildString(data));
}

/*************************** rjs.resizeLightbox.js ***************************/
/// <reference path="http://jqueryjs.googlecode.com/files/jquery-1.3.2-vsdoc2.js" />
; (function() {
var $ = jQuery,
continueResizing = false,
lastHeight,
lastKnownWrapperHeight,
loggingEnabled = false;
RJS.typeSequence("resize", function() {
loggingEnabled = !loggingEnabled;
window.console && console.log("toggled logging:", loggingEnabled);
});
function log() {
try {
if (loggingEnabled && window.console) {
if (typeof console != 'undefined' && typeof console.log == 'function') {
console.log.apply(console, arguments);
} else if (!Function.prototype.bind && typeof console != 'undefined' && typeof console.log == 'object') {
Function.prototype.call.call(console.log, console, Array.prototype.slice.call(arguments));
}
}
}catch (e) { }
}
function resizeLightbox() {
try {
var loadedContent = $("#cboxLoadedContent"),
iframe = loadedContent.children("iframe"),
isIframe = iframe.length > 0,
iframeDOM = iframe.get(0);
if (isIframe && (!iframe.is(":visible") || iframe.contents().length === 0)) {
if (continueResizing === true) {
setTimeout(resizeLightbox, resizeLightbox.updateInterval);
}
return;
}
if (isIframe) {
var innerDoc = iframeDOM.contentDocument || iframeDOM.contentWindow.document;
var innerWindow = innerDoc.defaultView || iframeDOM.contentWindow;
if (!innerWindow.jQuery || !innerWindow.jQuery.isReady || !innerDoc) {
if (continueResizing === true) {
setTimeout(resizeLightbox, resizeLightbox.updateInterval);
}
return;
}
var innerBody = innerDoc.body;
var temp = innerBody.getElementsByTagName("FORM");
//log('form: ', temp);
if (temp.length > 0) {
var innerForm = temp[0];
}
}
var growHeight = 0,
actualHeight;
if (innerForm) {
actualHeight = innerForm.scrollHeight;
} else {
actualHeight = loadedContent.get(0).scrollHeight;
}
if (lastHeight) {
growHeight = actualHeight - lastHeight;
}
if (growHeight != 0) {
var wrapper = $("#cboxWrapper"),
currentHeight = wrapper.height();
if (lastKnownWrapperHeight && currentHeight > 9000 && lastKnownWrapperHeight < 9001) {
log('lastKnownHeight: ', lastKnownWrapperHeight, ' grow by: ', growHeight);
var magicNumber = 23;// Not sure why, but this magic number is needed to make the lightbox grow the correct amount in this code path...
$.colorbox.resize({ height: (lastKnownWrapperHeight + growHeight + magicNumber) });
} else {
log('current height: ', currentHeight, ' grow by: ', growHeight);
$.colorbox.resize({ height: (currentHeight + growHeight) });
lastKnownWrapperHeight = currentHeight;
}
}
lastHeight = actualHeight;
} catch (e) { log(e); }
if (continueResizing === true) {
setTimeout(resizeLightbox, resizeLightbox.updateInterval);
}
}
$(document).bind('cbox_complete', function() {
lastHeight = null;
continueResizing = true;
setTimeout(resizeLightbox, resizeLightbox.updateInterval);
}).bind('cbox_cleanup', function() {
continueResizing = false;
lastHeight = null;
});
resizeLightbox.updateInterval = 150;
})();

/*************************** rjs.store.js ***************************/
; (function($) {
RJS.Store = RJS.Store || {};
RJS.Store.setupCarousel = setupCarousel;
RJS.Store.loadCarousel = loadCarousel;
RJS.Store.loadDelayedCarousels = loadDelayedCarousels;
RJS.Store.CCCrypto = function CCCrypto(settings) {
var s = settings || {
url: "",
merchantId: "",
modulus: "",
publicExp: "",
signature: "",
timestamp: "",
sysIndicator: "",
service: ""
};
var self = this,
rsa = new RJS.RSAKey(),
cardNumberInput,
encryptedTokenInput,
cardTypeSelect,
lightboxDiv,
lightboxErrorMessageElement,
controlsRegistered = false,
tokenized = false,
tokenizing = false,
lastCardType,
lastGoodValue,
lastBadValue,
lastErrorMessage = "",
lastErrorDisplayType = "INLINE";
rsa.setPublic(s.modulus, s.publicExp);
function luhn10Validation(number) {
// Set the string length and parity
var number_length = number.length;
var parity = number_length % 2;
// Loop through each digit and do the maths
var total = 0;
for (i = 0; i < number_length; i++) {
var digit = number.charAt(i);
// Multiply alternate digits by two
if (i % 2 == parity) {
digit = digit * 2;
// If the sum is two digits, add them together (in effect)
if (digit > 9) {
digit = digit - 9;
}
}
// Total up the digits
total = total + parseInt(digit);
}
return total % 10 === 0;
}
function removeValidationContainer() {
cardNumberInput.parent().children(".validation-error").remove();
}
function success(response) {
var valid = response === true;
var element = encryptedTokenInput.get(0);
var validator = RJS.Validate.getValidator();
if (valid) {
$(cardNumberInput).removeClass('invalid');
var submitted = validator.formSubmitted;
validator.prepareElement(element);
validator.formSubmitted = submitted;
validator.successList.push(element);
validator.showErrors();
} else {
if (lastErrorDisplayType === "MODAL") {
lightboxErrorMessageElement.html(lastErrorMessage);
setTimeout(function() {
jQuery('<a></a>').colorbox({ inline: true, href: "#" + lightboxDiv.attr("id"), title: 'Card Error', scrolling: false, transition: 'none', open: true, width: '500px' });
}, 500);
} else {
$(cardNumberInput).addClass('invalid');
var errors = {};
errors[element.name] = lastErrorMessage;
validator.showErrors(errors);
}
}
validator.stopRequest(element, valid);
}
// The 'rc' property of callback argument should have a value of "100" for success
// The 'token' property of the callback argument will contain the encrypted card number token
function getToken(cardNumber, cardType, callback) {
if (!cardNumber) throw "Invalid cardNumber value when calling getToken(...)";
if (!cardType) throw "Invalid cardType value when calling getToken(...)";
if (!$.isFunction(callback)) throw "Callback must be a function when calling getToken(...)";
var number = cardNumber.replace(/\D/g, '');
if ((cardType == "A" && number.length != 15) || (cardType != "A" && number.length != 16)) {
callback("Invalid card number.");
return;
}
if (!luhn10Validation(number)) {
callback("Invalid card number.");
return;
}
var encryptedCardNumber = RJS.Base64.encodeFromHex(rsa.encrypt(number));
var input = {
"pan": encryptedCardNumber,
"sig": s.signature,
"si": s.sysIndicator,
"type": cardType,
"ts": s.timestamp,
"service": s.service
};
window.console && console.log('Validating card through AJAX...');
startRequest(encryptedTokenInput[0]);
var sentCallback = false;
setTimeout(function timeoutSafety() {
if (!sentCallback) {
window.console && console.log('Tokenization timed out');
sentCallback = true;
callback.apply(this, ["TIMEOUT"]);
}
}, 5000);
var jsonPUrl = s.url + "?merchantID=" + s.merchantId + "&jsonstring=" + JSON.stringify(input) + "&callback=?";
$.getJSON(jsonPUrl, function completed() {
if (!sentCallback) {
sentCallback = true;
callback.apply(this, arguments);
}
});
};
function startRequest(element) {
var v = RJS.Validate.getValidator();
if (!v.pending[element.name]) {
v.pendingRequest++;
v.pending[element.name] = true;
}
};
function endRequest(element, valid, triggerValidation) {
var v = RJS.Validate.getValidator();
v.pendingRequest = 0;
// sometimes synchronization fails, make sure pendingRequest is never < 0
delete v.pending[element.name];
if (valid && v.pendingRequest == 0 && v.formSubmitted && v.form()) {
$(v.currentForm).submit();
} else if (!valid && v.pendingRequest == 0 && v.formSubmitted) {
$(v.currentForm).triggerHandler("invalid-form", [v]);
}
};
var originalErrorPlacement = RJS.Validate.standardOptions.errorPlacement;
function storeErrorPlacement() {
if (arguments[1] == encryptedTokenInput && lastErrorDisplayType === "MODAL") {
cardNumberInput.removeClass('invalid');
lightboxErrorMessageElement.html(lastErrorMessage);
setTimeout(function() {
jQuery('<a></a>').colorbox({ inline: true, href: "#" + lightboxDiv.attr("id"), title: 'Card Error', scrolling: false, transition: 'none', open: true, width: '500px' });
}, 500);
} else {
originalErrorPlacement.apply(null, arguments);
}
}
self.registerValidationOptions = function registerValidationOptions() {
var o = { errorPlacement: storeErrorPlacement };
var validator = RJS.Validate.getValidator();
$.extend(validator.settings, o);
};
self.registerControls = function registerControls(cardNumberTextbox, encryptedTokenHiddenField, cardTypeDropDown, lightboxContainer, lightboxMessageContainer) {
cardNumberInput = $(cardNumberTextbox);
encryptedTokenInput = $(encryptedTokenHiddenField);
cardTypeSelect = $(cardTypeDropDown);
lightboxDiv = $(lightboxContainer);
lightboxErrorMessageElement = $(lightboxMessageContainer);
controlsRegistered = true;
if (encryptedTokenInput.val().length > 0) {
window.console && console.log('Card saved. I won\'t validate unless you change it.');
lastGoodValue = cardNumberInput.val();
lastCardType = cardTypeSelect.val();
tokenized = true;
}
};
self.getLastErrorMessage = function getLastErrorMessage() { return lastErrorMessage; };
self.validate = function validate() {
if (!controlsRegistered) throw "registerControls(...) must be called before a card number can be validated.";
var triggerValidation = typeof this.id === "undefined";
var value = cardNumberInput.val();
var cardType = cardTypeSelect.val();
if (triggerValidation) cardNumberInput.removeClass("invalid");
if ($.trim(value).length == 0) {
if (triggerValidation) cardNumberInput.addClass("invalid");
lastErrorMessage = "Please enter your card number";
lastErrorDisplayType = "INLINE";
window.console && console.log("Invalid card.");
return false;
}
if (lastGoodValue === value && cardType == lastCardType) {
lastErrorMessage = "";
window.console && console.log("Valid card (no change).");
if (triggerValidation) removeValidationContainer();
return true;
} else if (lastGoodValue != value && tokenized) {
tokenized = false;
encryptedTokenInput.val("");
}
if (lastBadValue === value && cardType == lastCardType) {
lastGoodValue = null;
if (triggerValidation) cardNumberInput.addClass("invalid");
window.console && console.log("Invalid card (no change).");
return false;
}
lastCardType = cardType;
if (value.length < 15) {
if (triggerValidation) cardNumberInput.addClass("invalid");
lastErrorMessage = "Invalid card number.";
lastErrorDisplayType = "INLINE";
lastBadValue = value;
lastGoodValue = null;
window.console && console.log("Invalid card.");
return false;
}
if (!cardType || cardType == "") {
lastGoodValue = null;
lastErrorMessage = "";
lastErrorDisplayType = "INLINE";
window.console && console.log("No card type.");
return false;
}
if (tokenizing) return "pending";
var tokenizeStartDate = new Date();
tokenizing = true;
getToken(value, cardType, function callback(result) {
var tokenizeFinishedDate = new Date();
var elapsedMilliseconds = tokenizeFinishedDate.getTime() - tokenizeStartDate.getTime();
if (typeof result === "string") {
if (result === "TIMEOUT")
lastErrorMessage = "Card number could not be validated at this time. Please try again later.";
else
lastErrorMessage = result;
endRequest(encryptedTokenInput[0], false, triggerValidation);
if (triggerValidation) cardNumberInput.addClass("invalid");
lastErrorDisplayType = "INLINE";
lastBadValue = value;
lastGoodValue = null;
tokenized = false;
tokenizing = false;
if (triggerValidation) success(false);
window.console && console.log("Invalid card. Validated in " + elapsedMilliseconds + " milliseconds.");
return;
}
if (result.rc == 100) {
encryptedTokenInput.val(result.token);
lastGoodValue = value;
tokenized = true;
tokenizing = false;
if (triggerValidation) success(true);
if (triggerValidation) removeValidationContainer();
endRequest(encryptedTokenInput[0], true, triggerValidation);
window.console && console.log("Valid card. Validated in " + elapsedMilliseconds + " milliseconds.");
return;
}
if (result.rc == 105) {//BAD BIN
lastErrorDisplayType = "MODAL";
lastErrorMessage = "Rogers On Demand Online can only accept Canadian credit cards and cannot accept pre-paid or gift cards at this time.  Please try a different card.";
lastBadValue = value;
lastGoodValue = null;
tokenized = false;
tokenizing = false;
if (triggerValidation) success(false);
endRequest(encryptedTokenInput[0], false, triggerValidation);
window.console && console.log("Invalid card. Validated in " + elapsedMilliseconds + " milliseconds.");
return;
}
if (triggerValidation) cardNumberInput.addClass("invalid");
lastErrorDisplayType = "INLINE";
lastErrorMessage = 'Invalid card number.';
lastBadValue = value;
lastGoodValue = null;
tokenized = false;
tokenizing = false;
if (triggerValidation) success(false);
endRequest(encryptedTokenInput[0], false, triggerValidation);
window.console && console.log("Invalid card. Validated in " + elapsedMilliseconds + " milliseconds.");
});
return "pending";
};
};
var delayedCarousels = [];
function loadDelayedCarousels() {
for (var i = 0; i < delayedCarousels.length; i++) {
var o = delayedCarousels[i];
var movieScroll = o.container.find("div.movie-scroll");
var html = jQuery.processTemplateToText(RJS.Templates.assetStoreCarousel, o.data.assets);
movieScroll.empty();
movieScroll.append(html);
setupCarousel(o.container, movieScroll);
RJS.User.applyUserSettingsToAssets();
}
}
function loadCarousel(url, container, delayDisplay) {
$.ajax({
url: url,
dataType: "json",
success: function(data) {
if (delayDisplay) {
delayedCarousels.push({ container: container, data: data });
return;
}
var movieScroll = container.find("div.movie-scroll");
var html = jQuery.processTemplateToText(RJS.Templates.assetStoreCarousel, data.assets);
movieScroll.empty();
movieScroll.append(html);
setupCarousel(container, movieScroll);
RJS.User.applyUserSettingsToAssets();
},
error: function() {
window.console && console.log("ERROR: ", arguments);
}
});
}
function setupCarousel(container, movieScroll) {
if (typeof movieScroll === "undefined") {
movieScroll = container.find("div.movie-scroll");
}
var itemCount = movieScroll.children().children().length;
var scroll = 5;
var pages = Math.ceil(itemCount / scroll);
if (itemCount % scroll !== 0) {
var spacersToAdd = scroll - (itemCount % scroll);
for (var i = 0; i < spacersToAdd; i++) {
movieScroll.children().append('<li class="col"></li>');
}
itemCount = movieScroll.children().children().length;
pages = Math.ceil(itemCount / scroll);
}
var btnNext = $("a.next", container).get(0);
var btnPrev = $("a.prev", container).get(0);
var btnGoArray = null;
var pager = container.find("ul.paging");
if (pager.length > 0) {
var pagingTemplate = getPaginationTemplate(pages);
pager.append(pagingTemplate);
if (pages > 1) {
btnGoArray = getGoArray(pager.children(), pages, scroll);
}
}
movieScroll.jCarouselLite({
btnNext: btnNext,
btnPrev: btnPrev,
btnGo: btnGoArray,
easing: "swing",
visible: scroll,
start: 0,
scroll: scroll,
speed: 350,
circular: false,
afterEnd: function afterEnd(listItems) {
var listParent = listItems.eq(0).closest("div.carousel");
var pagingList = listParent.prev().find("ul.paging");
if (pagingList.length > 0) {
var match = listItems.selector.match(/\.slice\((\d*)\)/);
if (match != null && match.length > 1) {
var index = match[1];
var page = Math.floor(index / 5) + 1;
pagingList.find("a." + page).parent().addClass("current").siblings().removeClass("current");
} else {
window.console && console.log("couldn't determine page number: ", listItems.selector);
}
}
}
});
if (pages === 1) {
$(btnNext).addClass("disabled");
}
var width = movieScroll.width();
movieScroll.width(0);
movieScroll.animate({ width: width }, 'normal');
function getGoArray(pageList, pages, scroll) {
var btnGoArray = [];
var items = pageList;
for (var i = 0; i < pages * scroll; i++) {
if (i % scroll === 0) {
btnGoArray.push(items.eq(i / scroll));
} else {
btnGoArray.push("NoSelector");
}
}
return btnGoArray;
};
function getPaginationTemplate(pages) {
var html = "";
for (var i = 1; i <= pages; i++) {
html += '<li><a class="' + i + '" href="javascript:;">' + i + '</a></li>';
}
var items = $(html);
items.eq(0).addClass("current");
return items;
};
};
})(jQuery);

/*************************** rjs.suggest.js ***************************/
RJS.Suggest = function(ele, options) { // required: page, totalPages
options = Object.extend({
id: "suggest",
rangeLength: 5,
noresults: "No results were found.",
maxHeight: 255,
maxEntries: 25,
offsetX: -2,
offsetY: 0,
templates: { itemTemplate: jQuery.createTemplate('<div><p>{$T.name}</p></div>') }
}, options);
if (!(ele = $(ele))) throw ("RJS.Suggest element not found");
if (typeof options.url == "undefined") throw ('RJS.Suggest url is null, must be set to the handler that gives suggestions');
options.url = URLUtil.resolveUrl(options.url);
var cache = RJS.Cache();
var builder = null;
if (options.getTemplateName) {
builder = RJS.Repeater({ templates: options.templates, getTemplateName: options.getTemplateName });
} else {
builder = RJS.Repeater({ templates: options.templates });
}
var pe, rd, halt, current, lastQuery;
var start = function() {
halt = false;
return pe || (pe = new PeriodicalExecuter(request, 0.2));
};
var stop = function() {
rd.hide();
halt = true;
lastQuery = current = null;
};
var request = function() {
var query = ele.value;
if (query.strip() == "") return stop();
if (halt || compare(query, lastQuery)) return;
lastQuery = query;
var result = cache.find(function(ce) { return compare(ce.query, query) });
if (result) return display(result);
new Ajax.Request(options.url, {
method: 'get',
parameters: { q: query },
onException: function(resp, err) {
window.console && console.log(err);
},
onSuccess: function(resp) {
cache.update(resp.responseJSON);
display(resp.responseJSON);
}
});
};
var display = function(result) {
if (result.suggestions.length <= 0) return stop();
rd.update(builder.buildString(result.suggestions));
current = {
index: -1,
suggestions: result.suggestions,
nodes: rd.childElements().each(wireup)
};
rd.show();
};
var wireup = function(d) {
d.observe("mouseover", mouse);
d.observe("mouseout", mouse);
d.observe("mousedown", mouse);
};
var keyup = function(event) {
switch (event.keyCode) {
case Event.KEY_LEFT:
case Event.KEY_RIGHT:
halt = true;
break;
case Event.KEY_UP:
if (current) setSelected(current.index - 1, true);
break;
case Event.KEY_DOWN:
if (current) setSelected(current.index + 1, true);
break;
case Event.KEY_RETURN:
case Event.KEY_TAB:
break;
default:
halt = false;
}
};
// case insensitive compare that ignores multiple spaces
var compare = function(str1, str2) {
if (str1) str1 = str1.replace(/\s{2,}/g, " ");
if (str2) str2 = str2.replace(/\s{2,}/g, " ");
return (str1 == str2);
}
var mouse = function(event) {
if (!current) return;
switch (event.type) {
case "mouseover":
setSelected(current.nodes.indexOf(this));
break;
case "mouseout":
setSelected(-1);
break;
case "mousedown":
setSelected(current.nodes.indexOf(this));
accept();
break;
}
};
var setSelected = function(i, setval) {
if (i < 0 || i >= current.suggestions.length) return;
if (current.index != -1) $(current.nodes[current.index]).removeClassName("selected");
if (setval) ele.setValue(current.suggestions[i].name);
$(current.nodes[i]).addClassName("selected");
current.index = i;
halt = true;
};
var accept = function() {
ele.value = current.suggestions[current.index].name;
ele.fire('Suggest:accept', {});
halt = true;
};
ele.setAttribute("AutoComplete", "off");
ele.observe("keyup", keyup);
ele.observe("focus", start);
ele.observe("blur", stop);
rd = $(document.createElement("DIV"));
rd.id = options.id;
function calcpos() {
rd.clonePosition(ele, { setHeight: false, setWidth: false, offsetLeft: options.offsetX, offsetTop: ele.offsetHeight + options.offsetY });
}
calcpos();
rd.hide();
document.body.appendChild(rd);
Event.observe(window, "resize", calcpos);
return ele;
}

/*************************** rjs.tbpager.js ***************************/
RJS.TBPager = function (id, element, options) {
if (!(element = $(element))) throw new Error("RJS.TBPager passed a invalid element!");
options = Object.extend({
rangeLength: 5,
baseUrl: window.location.protocol + "//" + window.location.host + window.location.pathname,
query: window.location.search.toQueryParams()
}, options);
var page = options.page || 1;
if (typeof options.totalPages == "undefined" || !options.totalPages) throw new Error('RJS.TBPager totalPages is required');
var setPage = function (val, requestFromFilter) {
if (val < 0 || val > options.totalPages) return;
if (page == val) return;
page = val;
build();
//only fire this event if the request came from the pager.  If it comes from the filter, do not fire because this will make multiple requests to assetJSON
if (requestFromFilter != true)
document.fire('Pager:pageClick', { id: id, page: page });
}
var setTotalPages = function (i, requestFromFilter) {
options.totalPages = i;
//if current page has exceeded total pages or if the current page is 0, go back to page 1, or go to page 0 if there are no pages at all
if (page > options.totalPages || page === 0) {
setPage(options.totalPages == 0 ? 0 : 1, requestFromFilter);
}
else {
//when the request comes from a filter, we want to reset the pager and go back to the first page, so go back to page 1, or go to page 0 if there are no pages at all
if (requestFromFilter == true) {
if (options.totalPages == 0)
page = 0;
else
page = 1;
}
build();
}
}
var html = function () {
if (isNaN(page)) return;
var n = {
page: page,
totalPages: options.totalPages,
first: page > 1 ? '<li><a class="first" href="javascript:;"><span>|&lt;</span></a></li>' : '',
prev: page > 1 ? '<li><a class="previous" href="javascript:;"><span>&lt;</span></a></li>' : '',
next: page < options.totalPages ? '<li><a class="next" href="javascript:;"><span>&gt;</span></a></li>' : '',
last: page < options.totalPages ? '<li><a class="last" href="javascript:;"><span>&gt;|</span></a></li>' : ''
};
var t = jQuery.createTemplate('{$T.first} {$T.prev} <li><input type="text" id="total" value="{$T.page}"></input></li><li><span>of</span> {$T.totalPages} {$T.next} {$T.last}');
return jQuery.processTemplateToText(t, n);
}
var keypress = function (e) {
if (e.keyCode == Event.KEY_RETURN) {
e.stop();
var i = parseInt(this.value);
if (!isNaN(i))
setPage(i);
else
this.value = "";
}
}
var focus = function (e) {
this.value = "";
}
var build = function () {
var e = element.update(html());
e.select('a').invoke("observe", "click", click);
e.select('input').each(function (i) {
i.observe("keypress", keypress);
i.observe("focus", focus);
});
}
var click = function (evt) {
var ele = evt.element();
if (ele.className == 'previous')
setPage(page - 1);
else if (ele.className == 'next')
setPage(page + 1);
else if (ele.className == 'first')
setPage(1);
else if (ele.className == 'last')
setPage(options.totalPages);
evt.stop();
}
build();
return { setTotalPages: setTotalPages, setPage: setPage };
}

/*************************** rjs.templates.js ***************************/
RJS.Templates = {
assetClip: jQuery.createTemplate('\
<div class="video-wrap">\
<div class="video"><ul>\
<li>\
<div class="thumb" rel="{$T.infoUrl}">\
{$T.promo == null ? "" : "<span class=\\"promo-overlay\\">" + $T.promo + "</span>"}\
<a class="play" rel="{$T.infoUrl}" href="{$T.playUrl}">play video</a>\
<a class="fltlft" href="{$T.playUrl}" rel="{$T.infoUrl}"><img title="" alt="" src="{$T.assetThumbUrl}"/></a>\
</div>\
<div class="util">\
<ul class="iconGroup">\
{#if $T.price}\
<li class="entitle"><div class="price" rel="{$T.id}" rev="{$T.watchUrl}">{$T.price}</div></li>\
{#else}\
<li><span class="fltlft icon tv"></span></li>\
<li class="entitle"><div class="entitlement {$T.premiumStatus}" rel="{$T.entitlement}"></div></li>\
{#/if}\
</ul>\
<a href="{URLUtil.resolveUrl(\'~/account/playlist\')}" class="favorite add fltrght" rel="{$T.id}"></a>\
</div>\
<div class="clrbth"></div>\
<h2 class="video-title"><a href="{$T.playUrl}">{$T.titleName + ($T.showAssetName ? (": <span>" + $T.name + "</span>") : "")}</a></h2>\
<p>\
{$T.season} ({$T.length}) \
</p>\
<div class="clrbth"></div>\
<p>\
<a href="{$T.genreUrl}"><span>{$T.genre}</span></a> | <a runat="server" class="ratingsInfo" rel="{$T.ratingsUrl}" href="javascript:;"><span>{$T.parentalRating} </span></a> \
</p>\
<ul class="rated"><li class="rating" style="width: {($T.avgUserRating * 15) + (Math.ceil($T.avgUserRating) * 4)}px;"></li></ul>\
</li>\
</ul>\
</div></div>'),
assetClipHome: jQuery.createTemplate('\
<div class="video-wrap">\
<div class="video"><ul>\
<li>\
<div class="thumbAlt" rel="{$T.infoUrl}">\
{$T.promo == null ? "" : "<span class=\\"promo-overlay\\">" + $T.promo + "</span>"}\
<a class="play" rel="{$T.infoUrl}" href="{$T.playUrl}">play video</a>\
<a class="fltlft" href="{$T.playUrl}" rel="{$T.infoUrl}"><img title="" alt="" src="{$T.assetThumbUrl}"/></a>\
</div>\
<div class="util">\
<ul class="iconGroup">\
{#if $T.price}\
<li class="entitle"><div class="price" rel="{$T.id}" rev="{$T.watchUrl}">{$T.price}</div></li>\
{#else}\
<li><span class="fltlft icon tv"></span></li>\
<li class="entitle"><div class="entitlement {$T.premiumStatus}" rel="{$T.entitlement}"></div></li>\
{#/if}\
</ul>\
<a href="{URLUtil.resolveUrl(\'~/account/playlist\')}" class="favorite add fltrght" rel="{$T.id}"></a>\
</div>\
<div class="clrbth"></div>\
<h2 class="video-title"><a href="{$T.playUrl}">{$T.titleName + ($T.showAssetName ? (": <span>" + $T.name + "</span>") : "")}</a></h2>\
<p>\
{$T.season} ({$T.length}) \
</p>\
<div class="clrbth"></div>\
<p>\
<a href="{$T.genreUrl}"><span>{$T.genre}</span></a> | <a runat="server" class="ratingsInfo" rel="{$T.ratingsUrl}" href="javascript:;"><span>{$T.parentalRating} </span></a> \
</p>\
<ul class="rated"><li class="rating" style="width: {($T.avgUserRating * 15) + (Math.ceil($T.avgUserRating) * 4)}px;"></li></ul>\
</li>\
</ul>\
</div></div>'),
assetTvShow: jQuery.createTemplate('\
<div class="video-wrap">\
<div class="video"><ul>\
<li>\
<div class="thumb" rel="{$T.infoUrl}">\
{$T.promo == null ? "" : "<span class=\\"promo-overlay\\">" + $T.promo + "</span>"}\
<a class="play" rel="{$T.infoUrl}" href="{$T.playUrl}">play video</a>\
<a class="fltlft" href="{$T.playUrl}" rel="{$T.infoUrl}"><img title="" alt="" src="{$T.assetThumbUrl}"/></a>\
</div>\
<div class="util">\
<ul class="iconGroup">\
<li><span class="fltlft icon tv"></span></li>\
<li class="entitle"><div class="entitlement {$T.premiumStatus}" rel="{$T.entitlement}"></div></li>\
</ul>\
<a href="{URLUtil.resolveUrl(\'~/account/playlist\')}" class="favorite add fltrght" rel="{$T.id}"></a>\
</div>\
<div class="clrbth"></div>\
<h2 class="video-title"><a href="{$T.playUrl}">{$T.titleName + ($T.showAssetName ? (": <span>" + $T.name + "</span>") : "")}</a></h2>\
<p>\
{$T.season} ({$T.length})\
</p>\
<div class="clrbth"></div>\
<p>\
<a href="{$T.genreUrl}"><span>{$T.genre}</span></a> | <a runat="server" class="ratingsInfo" rel="{$T.ratingsUrl}" href="javascript:;"><span>{$T.parentalRating}</span></a>\
</p>\
<ul class="rated"><li class="rating" style="width: {($T.avgUserRating * 15) + (Math.ceil($T.avgUserRating) * 4)}px;"></li></ul>\
</li>\
</ul>\
</div></div>'),
genreTVShow: jQuery.createTemplate('\
<h2><a href="{$T.genreUrl}">{$T.genre}</a></h2>\
<div class="video-wrap">\
<div class="video">\
<ul>\
<li>\
<div class="thumb">\
{$T.promo == null ? "" : "<span class=\\"promo-overlay\\">" + $T.promo + "</span>"}\
<a href="{$T.playUrl}" rel="{$T.infoUrl}" class="play">play video</a>\
<a class="fltlft" href="{$T.playUrl}" rel="{$T.infoUrl}"><img title="" alt="" src="{$T.assetThumbUrl}"/></a>\
</div>\
<div class="util">\
<ul class="iconGroup">\
<li><span class="fltlft icon tv"></span></li>\
<li class="entitle"><div class="entitlement {$T.premiumStatus}" rel="{$T.entitlement}"></div></li>\
</ul>\
<a href="{URLUtil.resolveUrl(\'~/account/playlist\')}" class="favorite add fltrght" rel="{$T.id}"></a>\
</div>\
<h2 class="video-title"><a href="{$T.playUrl}">{$T.titleName + ($T.showAssetName ? (": <span>" + $T.name + "</span>") : "")}</a></h2>\
<p>\
{$T.season} ({$T.length})\
</p>\
<p>\
<a href="{$T.genreUrl}"><span>{$T.genre}</span></a> | <a runat="server" class="ratingsInfo" rel="{$T.ratingsUrl}" href="javascript:;"><span>{$T.parentalRating} </span></a>\
</p>\
<ul class="rated"><li class="rating" style="width: {($T.avgUserRating * 15) + (Math.ceil($T.avgUserRating) * 4)}px;"></li></ul>\
</li>\
</ul>\
</div>\
</div>\
'),
genreMovie: jQuery.createTemplate('\
<h2><a href="{$T.genreUrl}">{$T.genre}</a></h2>\
<div class="video-wrap">\
<div class="video">\
<ul>\
<li>\
<div class="thumb">\
{$T.promo == null ? "" : "<span class=\\"promo-overlay\\">" + $T.promo + "</span>"}\
<a href="{$T.playUrl}" rel="{$T.infoUrl}" class="play">play video</a>\
<a class="fltlft" href="{$T.playUrl}" rel="{$T.infoUrl}"><img title="" alt="" src="{$T.assetThumbUrl}"/></a>\
</div>\
<div class="util">\
<ul class="iconGroup">\
{#if $T.price}\
<li class="entitle"><div class="price" rel="{$T.id}" rev="{$T.watchUrl}">{$T.price}</div></li>\
{#else}\
<li><span class="fltlft icon movie"></span></li>\
<li class="entitle"><div class="entitlement {$T.premiumStatus}" rel="{$T.entitlement}"></div></li>\
{#/if}\
</ul>\
<a href="{URLUtil.resolveUrl(\'~/account/playlist\')}" class="favorite add fltrght" rel="{$T.id}"></a>\
</div>\
<h2 class="video-title"><a href="{$T.playUrl}">{$T.titleName + ($T.showAssetName ? (": <span>" + $T.name + "</span>") : "")}</a></h2>\
<p>({$T.length})</p>\
<p>\
<a href="{$T.genreUrl}"><span>{$T.genre}</span></a> | <a runat="server" class="ratingsInfo" rel="{$T.ratingsUrl}" href="javascript:;"><span>{$T.parentalRating} </span></a>\
</p>\
<ul class="rated"><li class="rating" style="width: {($T.avgUserRating * 15) + (Math.ceil($T.avgUserRating) * 4)}px;"></li></ul>\
</li>\
</ul>\
</div>\
</div>\
'),
assetMovie: jQuery.createTemplate('\
<div class="video-wrap">\
<div class="video">\
<ul>\
<li>\
<div class="thumb">\
{$T.promo == null ? "" : "<span class=\\"promo-overlay\\">" + $T.promo + "</span>"}\
<a class="play" rel="{$T.infoUrl}" href="{$T.playUrl}">play video</a>\
<a class="fltlft" href="{$T.playUrl}" rel="{$T.infoUrl}"><img title="" alt="" src="{$T.assetThumbUrl}"/></a>\
</div>\
<div class="util">\
<ul class="iconGroup">\
{#if $T.price} \
<li class="entitle"><div class="price" rel="{$T.id}" rev="{$T.watchUrl}">{$T.price}</div></li>\
{#else}\
<li><span class="fltlft icon movie"></span></li>\
<li class="entitle"><div class="entitlement {$T.premiumStatus}" rel="{$T.entitlement}"></div></li>\
{#/if}\
</ul>\
<a href="{URLUtil.resolveUrl(\'~/account/playlist\')}" class="favorite add fltrght" rel="{$T.id}"></a>\
</div>\
<div class="clrbth"></div>\
<h2 class="video-title"><a href="{$T.playUrl}">{$T.titleName + ($T.showAssetName ? (": <span>" + $T.name + "</span>") : "")}</a></h2>\
<p>({$T.length})</p>\
<div class="clrbth"></div>\
<p>\
<a href="{$T.genreUrl}"><span> {$T.genre}</span></a> | <a runat="server" class="ratingsInfo" rel="{$T.ratingsUrl}" href="javascript:;"><span>{$T.parentalRating}</span></a>\
</p>\
<ul class="rated"><li class="rating" style="width: {($T.avgUserRating * 15) + (Math.ceil($T.avgUserRating) * 4)}px;"></li></ul>\
</li>\
</ul>\
</div></div>'),
assetSportingEvent: jQuery.createTemplate('\
<div class="video-wrap">\
<div class="video">\
<ul>\
<li>\
<div class="thumb">\
{$T.promo == null ? "" : "<span class=\\"promo-overlay\\">" + $T.promo + "</span>"}\
<a class="play" rel="{$T.infoUrl}" href="{$T.playUrl}">play video</a>\
<a class="fltlft" href="{$T.playUrl}" rel="{$T.infoUrl}"><img title="" alt="" src="{$T.assetThumbUrl}"/></a>\
</div>\
<div class="util">\
<ul class="iconGroup">\
{#if $T.price} \
<li class="entitle"><div class="price" rel="{$T.id}" rev="{$T.watchUrl}">{$T.price}</div></li>\
{#else}\
<li><span class="fltlft icon tv"></span></li>\
<li class="entitle"><div class="entitlement {$T.premiumStatus}" rel="{$T.entitlement}"></div></li>\
{#/if}\
</ul>\
<a href="{URLUtil.resolveUrl(\'~/account/playlist\')}" class="favorite add fltrght" rel="{$T.id}"></a>\
</div>\
<div class="clrbth"></div>\
<h2 class="video-title"><a href="{$T.playUrl}">{$T.name}</a></h2>\
<p>({$T.length})</p>\
<div class="clrbth"></div>\
<p>\
<a href="{$T.genreUrl}"><span> {$T.genre}</span></a> | <a runat="server" class="ratingsInfo" rel="{$T.ratingsUrl}" href="javascript:;"><span>{$T.parentalRating}</span></a>\
</p>\
<ul class="rated"><li class="rating" style="width: {($T.avgUserRating * 15) + (Math.ceil($T.avgUserRating) * 4)}px;"></li></ul>\
</li>\
</ul>\
</div></div>'),
fullMovie: jQuery.createTemplate('\
<div class="fullMovie">\
<img src="{$T.boxArtLargeImageUrl}" alt="" title="" class="poster" />\
<div class="video-wrap">\
<div class="video">\
<ul>\
<li>\
<div class="thumb">\
{$T.promo == null ? "" : "<span class=\\"promo-overlay\\">" + $T.promo + "</span>"}\
<a href="{$T.playUrl}" rel="{$T.infoUrl}"  class="play">play video</a>\
<a class="fltlft" href="{$T.playUrl}" rel="{$T.infoUrl}"><img src="{$T.assetThumbUrl}" alt="" title="" /></a>\
</div>\
<div class="util">\
<ul class="iconGroup">\
{#if $T.price}\
<li class="entitle"><div class="price" rel="{$T.id}" rev="{$T.watchUrl}">{$T.price}</div></li>\
{#else}\
<li><span class="fltlft icon movie"></span></li>\
<li class="entitle"><div class="entitlement {$T.premiumStatus}" rel="{$T.entitlement}"></div></li>\
{#/if}\
</ul>\
<a href="{URLUtil.resolveUrl(\'~/account/playlist\')}" class="favorite add fltrght" rel="{$T.id}"></a>\
</div>\
<h2 class="video-title"><a href="{$T.playUrl}" >{$T.titleName + ($T.showAssetName ? (": <span>" + $T.name + "</span>") : "")}</a></h2>\
<p>\
({$T.length})<br />\
<a href="{$T.genreUrl}"><span>{$T.genre}</span></a> | <a runat="server" class="ratingsInfo" rel="{$T.ratingsUrl}" href="javascript:;"><span>{$T.parentalRating}</span></a>\
</p>\
<div class="clrbth"></div>\
<ul class="rated"><li class="rating" style="width: {($T.avgUserRating * 15) + (Math.ceil($T.avgUserRating) * 4)}px;"></li></ul>\
</li>\
</ul>\
</div>\
</div></div>'),
musicVideo: jQuery.createTemplate('\
<img src="{$T.cdArtImageUrl}" alt="" title="" class="cdArt" />\
<div class="video-wrap fullMusic">\
<div class="video">\
<ul>\
<li>\
<div class="thumb">\
{$T.promo == null ? "" : "<span class=\\"promo-overlay\\">" + $T.promo + "</span>"}\
<a href="{$T.playUrl}" rel="{$T.infoUrl}"  class="play">play video</a>\
<a class="fltlft" href="{$T.playUrl}" rel="{$T.infoUrl}"><img src="{$T.assetThumbUrl}" alt="" title="" /></a>\
</div>\
<div class="util">\
<ul class="iconGroup">\
<li><span class="fltlft icon tv"></span></li>\
<li class="entitle"><div class="entitlement {$T.premiumStatus}" rel="{$T.entitlement}"></div></li>\
</ul>\
<a href="{URLUtil.resolveUrl(\'~/account/playlist\')}" class="favorite add fltrght" rel="{$T.id}"></a>\
</div>\
<h2 class="video-title"><a href="{$T.playUrl}" >{$T.titleName + ($T.showAssetName ? (": <span>" + $T.name + "</span>") : "")}</a></h2>\
<p class="fltlft">\
({$T.length}) | <a runat="server" class="ratingsInfo" rel="{$T.ratingsUrl}" href="javascript:;"><span>{$T.parentalRating}</span></a> | Music Video\
</p>\
<ul class="rated"><li class="rating" style="width: {($T.avgUserRating * 15) + (Math.ceil($T.avgUserRating) * 4)}px;"></li></ul>\
</li>\
</ul>\
</div>\
</div>'),
channels: jQuery.createTemplate('<div class="channel-wrap">\
<div class="channel">\
<ul>\
<li><a href="{$T.navUrl}" class="channels" rel="{$T.infoUrl}"><img src="{$T.navImageUrl}" alt="{$T.name}" title="{$T.name}" /></a></li>\
</ul>\
</div>\
</div>'),
channelsList: jQuery.createTemplate('<p class="channelListView"><a class="channelsList" href="{$T.navUrl}" rel="{$T.infoUrl}">{$T.name}</a><p>'),
assetList: jQuery.createTemplate('<div class="video-wrap" id="listView">\
<div class="video">\
<div class="util">\
<ul class="iconGroup">\
<li><span class="fltlft icon tv"></span></li>\
<li>{$T.promo == null ? "" : "<span class=\\"promo-overlay\\">" + $T.promo + "</span>"}</li>\
<li class="entitle"><div class="entitlement {$T.premiumStatus}" rel="{$T.entitlement}"></div></li>\
</ul>\
<a href="{URLUtil.resolveUrl(\'~/account/playlist\')}" class="favorite add fltrght" rel="{$T.id}"></a>\
</div>\
<h2 class="video-title"><a href="{$T.playUrl}" rel="{$T.infoUrl}" class="FindbytitleInfo">{$T.titleName + ($T.showAssetName ? (": <span>" + $T.name + "</span>") : "")}</a></h2>\
<br/>\
<p> {$T.season} ({$T.length})\
<br />\
<a href="{$T.genreUrl}"><span>{$T.genre}</span></a> | <a runat="server" class="ratingsInfo" rel="{$T.ratingsUrl}" href="javascript:;"><span>{$T.parentalRating}</span></a></p>\
<br/>\
<ul class="rated"><li class="rating" style="width: {($T.avgUserRating * 15) + (Math.ceil($T.avgUserRating) * 4)}px;"></li></ul>\
\
</div>\
</div>'),
pagination: jQuery.createTemplate('<div class="pagination"><a href="">< Previous</a>{$T.contents}<a href=""> Next ></a></div>'),
comment: jQuery.createTemplate('<div id="{$T.id}" class="comment{($T.deleteDate == null ? \'\' : \' deleted\')}">\
<strong>Comment: Abuse Reported <a class="toggleVisibility" href="javascript:;">show</a></strong>\
<p class="reply fltrght"><a href="javascript:;" class="reply">Reply</a> | <a href="{URLUtil.resolveUrl(\'~/h/reportComment?comment=\' + $T.id)}" class="report" title="Report this comment">Report Abuse</a></p>\
<p class="username"><span class="username">{$T.userAlias}</span> <span class="commentTime" title="{$T.createDate}">{$T.createDate}</span></p>\
<p class="commentBody">{$T.comment}</p>\
<p class="deletedCommentBody">This comment violated our Terms of Service and has been removed.</p>\
</div>'),
assetStoreCarousel: jQuery.createTemplate('\
<ul>\
{#foreach $T as item}\
<li class="col video rental">\
{#if "promotionalMessage" in $T.item}\
<div class="new-rental">\
<div class="new-rental-wrap">\
<span></span>{$T.item.promotionalMessage == null ? "" : $T.item.promotionalMessage}\
</div>\
</div>\
{#/if}\
<div class="thumb"> \
<a class="play" href="{$T.item.playUrl}" rel="{$T.item.infoUrl}">play video</a> \
<a href="{$T.item.playUrl}" rel="{$T.item.infoUrl}"><img src="{$T.item.boxArtMediumImageUrl}" width="99" height="142" class="cover"  /></a> \
</div> \
<div class="movie-info fltlft"> \
<p class="price" rel="{$T.item.id}" rev="{$T.item.watchUrl}">{$T.item.price}</p> \
<h2 class="title"><a href="{$T.item.playUrl}">{$T.item.name}</a></h2> \
<a href="{URLUtil.resolveUrl(\'~/account/playlist\')}" class="favorite add" rel="{$T.item.id}"></a> \
<ul class="rated"><li class="rating" style="width: {($T.item.avgUserRating * 15) + (Math.ceil($T.item.avgUserRating) * 4)}px;"></li></ul>\
</div> \
</li>\
{#/for}\
</ul>', null, {isForArray: true}),
assetEditorsPicks: jQuery.createTemplate('\
{#foreach $T as item}\
<li class="video rental">\
<div class="thumb fltlft">\
<a class="play" href="{$T.item.playUrl}" rel="{$T.item.infoUrl}">play video</a> \
<a href="{$T.item.playUrl}" rel="{$T.item.infoUrl}"><img src="{$T.item.boxArtSmallImageUrl}" width="68" height="97" class="picks-img fltlft" /></a>\
</div>\
<div class="movie-info fltlft">\
<!-- Show this view when video is last-chance -->\
<div class="group last-chance">\
<p class="price" rel="{$T.item.id}" rev="{$T.item.watchUrl}">{$T.item.price}</p>\
{#if $T.item.justAdded}<img src="' + URLUtil.resolveUrl('~/')+ 'i/icons/last-chance-icon.png" alt="" width="12" height="12" />{#/if}\
</div>\
<!-- End -->\
<h2 class="title"><a href="{$T.item.playUrl}">{$T.item.name}</a></h2>\
<ul class="rated"><li class="rating" style="width: {($T.item.avgUserRating * 15) + (Math.ceil($T.item.avgUserRating) * 4)}px;"></li></ul>\
<a href="{URLUtil.resolveUrl(\'~/account/playlist\')}" class="favorite add" rel="{$T.item.id}"></a>\
</div>\
</li>\
{#/for}', null, {isForArray: true}),
assetLastChance: jQuery.createTemplate('\
<ul>\
{#foreach $T as item}\
<li {#if $T.$last}class="last"{#/if}>\
<div class="lc-row">\
<div class="group">\
<p class="price fltlft" rel="{$T.item.id}" rev="{$T.item.watchUrl}">{$T.item.price}</p>\
{#if ($T.item.expires.length > 0)}<p class="exp fltrght">Until. {$T.item.expires}</p>{#/if}\
</div>\
<h2 class="title"><a href="{$T.item.playUrl}" rel="{$T.item.infoUrl}" class="FindbytitleInfo">{$T.item.name}</a></h2>\
<ul class="rated"><li class="rating" style="width: {($T.item.avgUserRating * 15) + (Math.ceil($T.item.avgUserRating) * 4)}px;"></li></ul>\
</div>\
</li>\
{#/for}\
</ul>', null, {isForArray: true}),
assetBrowseTiles: jQuery.createTemplate('<div class="group" id="browse-grid">\
<ul>\
{#foreach $T as item}\
<li class="col video rental">\
<div class="thumb">\
<a class="play" href="{$T.item.playUrl}">play video</a>\
<a href="{$T.item.playUrl}" rel="{$T.item.infoUrl}"><img src="{$T.item.boxArtMediumImageUrl}" width="99" height="142" class="rental" /></a>\
</div>\
<a href="{URLUtil.resolveUrl(\'~/account/playlist\')}" class="favorite add" rel="{$T.item.id}"></a>\
<div class="movie-info fltlft">\
<p class="price" rel="{$T.item.id}" rev="{$T.item.watchUrl}">{$T.item.price}</p>\
<h2 class="title"><a href="{$T.item.playUrl}">{$T.item.name}</a></h2>\
<ul class="rated"><li class="rating" style="width: {($T.item.avgUserRating * 15) + (Math.ceil($T.item.avgUserRating) * 4)}px;"></li></ul>\
</div>\
</li>\
{#/for}\
</ul>\
</div>', null, {isForArray: true}),
assetBrowseList: jQuery.createTemplate('<div class="group" id="browse-list">\
<table id="browse-list-table" class="roundAll" cellpadding="0" cellspacing="0">\
<tbody>\
{#foreach $T as item}\
<tr{#if ($T.item$index%2==0)} class="even"{#/if}>\
<td class="list-title"><p class="fltlft"><span class="icon movie"></span></p><h2 class="title"><a href="{$T.item.playUrl}" rel="{$T.item.infoUrl}" class="FindbytitleInfo">{$T.item.name}</a></h2></td>\
<td class="list-price"><p class="price">{$T.item.price}</p></td>\
<td class="list-rating"><ul class="rated"><li class="rating" style="width: {($T.item.avgUserRating * 15) + (Math.ceil($T.item.avgUserRating) * 4)}px;"></li></ul></td>\
<td class="list-button"><a href="{$T.item.playUrl}" class="round-button details" rel="{$T.item.id}" rev="{$T.item.watchUrl}">Details</a></td>\
<td class="list-add video"><a href="{URLUtil.resolveUrl(\'~/account/playlist\')}" class="favorite add" rel="{$T.item.id}"></a></td>\
</tr>\
{#/for}\
</tbody>\
</table>\
</div>', null, {isForArray: true}),
assetHeroList: jQuery.createTemplate('\
<div>\
<h2>Carousel of Featured Videos</h2>\
<ul>\
{#foreach $T as item}\
<li>\
<a class="itemLink" href="{$T.item.playUrl}">\
<span>\
{$T.item.titleName + ($T.item.showAssetName ? (": " + $T.item.name) : "")}</strong>\
{($T.item.season != null && $T.item.season.length > 0) ? (" - " + $T.item.season) : ""} \
{($T.item.fullDescription != null && $T.item.fullDescription.length > 0) ? (" - " + $T.item.fullDescription) : ""}\
</span>\
</a>\
</li>\
{#/for}\
</ul>\
</div>\
', null, {isForArray: true}),
genreHeroList: jQuery.createTemplate('\
<div>\
<h2>Carousel of Shows</h2>\
<ul>\
{#foreach $T as item}\
<li>\
<a class="itemLink" href="{$T.item.navigationUrl}">\
<span>\
<strong>{$T.item.name}</strong>\
</span>\
</a>\
</li>\
{#/for}\
</ul>\
</div>\
', null, {isForArray: true}),
channelHeroList: jQuery.createTemplate('\
<div>\
<h2>Carousel of Channels</h2>\
<ul>\
{#foreach $T as item}\
<li>\
<a class="itemLink" href="{$T.item.navUrl}">\
<span>\
<strong>{$T.item.name}</strong>\
{($T.item.description != null && $T.item.description.length > 0) ? (" - " + $T.item.description) : ""}\
</span>\
</a>\
</li>\
{#/for}\
</ul>\
</div>\
', null, {isForArray: true})
};

/*************************** rjs.tooltip.js ***************************/
RJS.Tooltip = RJS.Tooltip || (function() {
var tooltipCounter = 0;
var triggerCounter = 0; // Used for assigning IDs for tooltip trigger elements if they do not have IDs
var instances = {};
var body = document.body;
var Tooltip = function(opts) {
var self = this;
var defaultOptions = {
instanceName: '', // Name given to this specific instance of the tooltip generator. Used to retrieve an instance using RJS.Tooltip.getInstance(name) for debugging. If no name is given, the instance is not stored and can not be retrieved by the RJS.Tooltip.getInstance(name) method.
context: document.body, // Context for event-delegation triggered tooltips and to define the boundary of where the tooltip should display
selector: null, // Selector for event-delegation triggered tooltips
position: 'auto', // Position to display tooltip in relation to its element. Auto starts at the right. Can be top, bottom, left, or right
direction: 'auto', // Which of the 6 positional properties to use initially for the tooltip. If using Auto, the tooltip will start on the right.
autoAdjust: false, // Whether the tooltip should automatically calculate a new position if there is not enough room to place it in its current position.
baseClass: 'info_hover', // Base class applied at the root of tooltip elements
rightClass: 'info_hover_right', // Class for tooltips displayed to the right of an element
rightBottomClass: 'info_hover_rightBottom', // Class for tooltips displayed below an element (from the right)
rightTopClass: 'info_hover_rightTop', // Class for tooltips displayed above an element (from the right)
leftClass: 'info_hover_left', // Class for tooltips displayed to the left of an element
leftBottomClass: 'info_hover_leftBottom', // Class for tooltips displayed below an element (from the left)
leftTopClass: 'info_hover_leftTop', // Class for tooltips displayed above an element (from the left)
dynamicContentElementSelector: '.dynamic-content', // CSS selector used to find the element to replace with actual content when an Ajax request is fulfilled. Tag selected with this selector will also be removed.
ajaxTimeout: 10000, // Duration to wait before an Ajax request is forcibly timed out. If set to zero, no timeout will be set.
adjustTop: 0, // Nudges the tooltip from the top if being displayed above the element
adjustBottom: 0, // Nudges the tooltip from the bottom if being displayed below the element
adjustRight: 0, // Nudges the tooltip from the right if being displayed to the right of the element
adjustLeft: 0, // Nudges the tooltip from the left if being dislayed to the left of the element
nudgeTop: 0, // Extra pixels added to the element's "top" positioning when placing the element. This is always applied unlike adjustTop.
nudgeLeft: 0, // Extra pixels added to the element's "left" positioning when placing the element. This is always applied unlike adjustLeft.
getAjaxUrl: function(e) {
// Some templates have title/alt tags on images/links. Remove them when displaying a tooltip
var attrsToRemove = e.select('[title], [alt]');
for (var i = 0; i < attrsToRemove.length; i++) {
attrsToRemove[i].writeAttribute('title', '');
attrsToRemove[i].writeAttribute('alt', '');
}
return e.readAttribute('rel') || e.select('a[rel]')[0].readAttribute('rel');
}, // Method called for retrieving AJAX data for the tooltip. First argument is the DOM element the tooltip is being shown for.
hoverIntentDelay: 275, // Time in milliseconds to delay showing the tooltip for when the mouse hovers over the tooltip target
show: 'mouseover', // Event to cause the tooltip to be displayed.
hide: 'mouseout', // Event to cause the tooltip to be hidden
content: null, // Content to display within the tooltip. This can be an HTML string, an Element, or a function that returns the element or string to include in the tooltip
ajaxUrl: null, // URL to use for getting tooltip info
element: null, // Specific element to assign a tooltip
ignoreTopContextBoundary: false, // Ignores the top edge of the context when calculating the tooltip's position. The visible edges of the screen are used instead.
ignoreBottomContextBoundary: false, // Ignores the bottom edge of the context when calculating the tooltip's position. The visible edges of the screen are used instead.
ignoreLeftContextBoundary: false, // Ignores the left edge of the context when calculating the tooltip's position. The visible edges of the screen are used instead.
ignoreRightContextBoundary: false, // Ignores the right edge of the context when calculating the tooltip's position. The visible edges of the screen are used instead.
contentLoadingTemplate: '<div class="loading"> </div>', // Template to display when loading content from an AJAX request.
tooltipTemplate: // Template used for tooltips
'<div>\
<div class="pointer"> </div>\
<div class="info-content">\
<div class="info-content-wrapper">\
<div class="info-top"> </div>\
<div class="info-top-left"> </div>\
<div class="info-top-right"> </div>\
<div class="info-bottom-left"> </div>\
<div class="info-bottom-right"> </div>\
<div class="info-h"> </div>\
<div class="info-v-left"> </div>\
<div class="info-v-right"> </div>\
<div class="dynamic-content"></div>\
</div>\
</div>\
</div>'
};
var currentDirection = null;
var flippedVertically = false;
var flippedHorizontally = false;
self.getDefaultOptions = function() { return Object.clone(defaultOptions); };
self.options = defaultOptions;
var activeTooltip = {
current: null,
set: function(tooltipId) {
RJS.Tooltip.hideAll();
if (jQuery.support.opacity) {
jQuery("#" + tooltipId).fadeIn(200);
} else {
$(tooltipId).style.display = 'block';
}
this.current = tooltipId;
},
unset: function() {
if (this.current != null) {
var current = document.getElementById(this.current);
if (current != null) {
if (jQuery.support.opacity) {
jQuery(current).fadeOut(200);
} else {
current.style.display = 'none';
}
this.current = null;
this.trigger = null;
}
}
}
};
self.hideActive = function() {
activeTooltip.unset();
};
var timeouts = {
list: {},
clear: function(key) {
var t = timeouts.list[key];
if (t) {
while (t.length > 0) {
var timeout = t.pop();
clearTimeout(timeout);
}
}
},
add: function(code, key) {
if (self.options.ajaxTimeout > 0) {// Don't initialize the timer if the timeout is zero (infinite)
if (!timeouts.list[key] || !timeouts.list[key].length) {
timeouts.list[key] = [];
}
timeouts.list[key].push(setTimeout(code, self.options.ajaxTimeout));
}
}
};
var getElementFromEventOrDefault = function(event) {
var o = self.options;
if (o.element == null) {
if (!("ancestors" in event.target))
return null;
return event.findElement(o.selector);
}
return o.element;
};
var getPositionOffset = function(tooltip, position) {
var ttDim = tooltip.getDimensions();
var retVal = null;
switch (position.toLowerCase()) {
case 'lefttopclass':
case 'righttopclass':
retVal = { left: (ttDim.width / 2) * -1, top: ttDim.height * -1 };
retVal.top += self.options.adjustTop;
break;
case 'leftbottomclass':
case 'rightbottomclass':
retVal = { left: (ttDim.width / 2) * -1, top: 0 };
retVal.top -= self.options.adjustBottom;
break;
case 'leftclass':
retVal = { left: ttDim.width * -1, top: (ttDim.height / 2) * -1 };
retVal.left += self.options.adjustLeft;
break;
case 'rightclass':
case 'auto':
default:
retVal = { left: 0, top: (ttDim.height / 2) * -1 };
retVal.left -= self.options.adjustRight;
}
return retVal;
};
var getPosition = function(element, position) {
var eDim = element.getDimensions();
var ePos = element.cumulativeOffset();
var contextPos = $(self.options.context).cumulativeOffset();
ePos = { left: (ePos.left - contextPos.left), top: (ePos.top - contextPos.top) };
var retVal = null;
switch (position.toLowerCase()) {
case 'lefttopclass':
case 'righttopclass':
retVal = { left: ePos.left + (eDim.width / 2), top: ePos.top };
break;
case 'leftbottomclass':
case 'rightbottomclass':
retVal = { left: ePos.left + (eDim.width / 2), top: ePos.top + eDim.height };
break;
case 'leftclass':
retVal = { left: ePos.left, top: ePos.top + (eDim.height / 2) };
break;
case 'rightclass':
case 'auto':
default:
retVal = { left: ePos.left + eDim.width, top: ePos.top + (eDim.height / 2) };
}
return retVal;
};
var getCurrentDirection = function(tooltip) {
if (currentDirection == null) {
var o = self.options;
if ($w(tooltip.className).size() > 1) {
if (tooltip.hasClassName(o.rightClass)) {
currentDirection = 'rightClass';
} else if (tooltip.hasClassName(o.rightBottomClass)) {
currentDirection = 'rightBottomClass';
} else if (tooltip.hasClassName(o.rightTopClass)) {
currentDirection = 'rightTopClass';
} else if (tooltip.hasClassName(o.leftClass)) {
currentDirection = 'leftClass';
} else if (tooltip.hasClassName(o.leftBottomClass)) {
currentDirection = 'leftBottomClass';
} else if (tooltip.hasClassName(o.leftTopClass)) {
currentDirection = 'leftTopClass';
}
if (currentDirection != null) {
return currentDirection;
}
}
currentDirection = o.direction == 'auto' ? 'rightClass' : o.direction;
}
return currentDirection;
};
var getElementEdges = function(element) {
var e = $(element);
var defaultVisibility = e.getStyle("visibility");
var defaultDisplay = e.getStyle("display");
if (defaultDisplay !== 'block') {
e.style.visibility = 'hidden';
e.style.display = 'block';
}
var offset = e.cumulativeOffset();
var dimensions = e.getDimensions();
var boundaries = {
top: offset.top,
right: offset.left + dimensions.width,
bottom: offset.top + dimensions.height,
left: offset.left
};
if (defaultDisplay !== 'block') {
e.setStyle({ "display": defaultDisplay });
e.setStyle({ "visibility": defaultVisibility });
}
return boundaries;
};
var getBoundaries = function(context) {
var boundaries = getElementEdges(context);
var o = self.options;
var viewportOffset = document.viewport.getScrollOffsets();
var viewportDimensions = document.viewport.getDimensions();
var viewport = {
top: viewportOffset.top,
right: viewportOffset.left + viewportDimensions.width,
bottom: viewportOffset.top + viewportDimensions.height,
left: viewportOffset.left
};
if (boundaries.top < viewport.top || o.ignoreTopContextBoundary)
boundaries.top = viewport.top;
if (boundaries.left < viewport.left || o.ignoreLeftContextBoundary)
boundaries.left = viewport.left;
if (boundaries.bottom > viewport.bottom || o.ignoreBottomContextBoundary)
boundaries.bottom = viewport.bottom;
if (boundaries.right > viewport.right || o.ignoreRightContextBoundary)
boundaries.right = viewport.right;
return boundaries;
}
var flipStyleHorizontal = function() {
if (currentDirection.indexOf('right') > -1) {
currentDirection = currentDirection.replace('right', 'left');
} else {
currentDirection = currentDirection.replace('left', 'right');
}
}
var flipStyleVertical = function(direction) {
if (currentDirection.indexOf('Top') > -1) {
currentDirection = currentDirection.replace('Top', 'Bottom');
} else if (currentDirection.indexOf('Bottom') > -1) {
currentDirection = currentDirection.replace('Bottom', 'Top');
} else if (currentDirection.indexOf('left') > -1 && direction == "u") {
currentDirection = 'leftTopClass';
} else if (currentDirection.indexOf('right') > -1 && direction == "u") {
currentDirection = 'rightTopClass';
} else if (currentDirection.indexOf('left')) {
currentDirection = 'leftBottomClass';
} else {
currentDirection = 'rightBottomClass';
}
}
var positionTooltip = function(element, tooltip, stackCount) {
var o = self.options;
var p = getCurrentDirection(tooltip);
stackCount = stackCount || 0;
var position = getPosition(element, p);
var offset = getPositionOffset(tooltip, p);
var contextPosition = o.context.cumulativeOffset();
var coords = { top: (position.top + offset.top), left: (position.left + offset.left) };
tooltip.style.top = (contextPosition.top + coords.top + o.nudgeTop) + "px";
tooltip.style.left = (contextPosition.left + coords.left + o.nudgeLeft) + "px";
tooltip.className = o.baseClass + ' ' + o[p];
if (!o.autoAdjust)
return;
if (stackCount < 3) {
var boundaries = getBoundaries(o.context);
var edges = getElementEdges(tooltip);
if (!flippedHorizontally && p.indexOf('right') > -1 && edges.right > boundaries.right) {
flipStyleHorizontal();
flippedVertically = true;
positionTooltip(element, tooltip, stackCount + 1);
} else if (!flippedHorizontally && p.indexOf('left') > -1 && edges.left < boundaries.left) {
flipStyleHorizontal();
flippedVertically = true;
positionTooltip(element, tooltip, stackCount + 1);
} else if (!flippedVertically && (p.indexOf('Top') > -1 || p.indexOf('Bottom') < 0) && edges.top < boundaries.top) {
flipStyleVertical("d");
flippedVertically = true;
positionTooltip(element, tooltip, stackCount + 1);
} else if (!flippedVertically && (p.indexOf('Bottom') > -1 || p.indexOf('Top') < 0) && edges.bottom > boundaries.bottom) {
flipStyleVertical("u");
flippedVertically = true;
positionTooltip(element, tooltip, stackCount + 1);
} else if (flippedVertically && (edges.bottom > boundaries.bottom || edges.top < boundaries.top)) {
currentDirection = currentDirection.replace('Top', '').replace('Bottom', '');
positionTooltip(element, tooltip, stackCount + 1);
}
}
if (stackCount === 0) {
currentDirection = null;
flippedHorizontally = false;
flippedVertically = false;
}
};
var createNewTooltip = function(element) {
var o = self.options;
var tooltip = $(createElement(o.tooltipTemplate));
tooltip.style.display = 'none';
$(body).insert(tooltip);
tooltip.id = 'tooltip-' + tooltipCounter;
element.setAttribute('tooltipID', tooltip.id);
tooltip.addClassName(o.baseClass);
if (o.content) {// Static Content
if (typeof o.content === "function") {
var e = tooltip.select(o.dynamicContentElementSelector)[0];
e.replace(o.content(element));
} else {
var e = tooltip.select(o.dynamicContentElementSelector)[0];
e.replace(o.content);
}
} else {// AJAX content
var dynamic = tooltip.select(o.dynamicContentElementSelector)[0];
dynamic.insert(o.contentLoadingTemplate);
var url = (o.ajaxUrl || o.getAjaxUrl(element));
tooltip.setAttribute('rel', url);
var request = new Ajax.Request(url, {
method: 'get',
onSuccess: function(transport) {
timeouts.clear(url);
if (dynamic.parentNode && (!transport || !transport.responseText || transport.responseText.length === 0)) {// <- IE7 throws an exception if this check isn't included
dynamic.replace('<div class="tooltip-wrap">Error occured while trying to retrieve information. Try again later.</div>');
setTimeout(function() {
tooltip.remove(); //Remove the tooltip. This will allow the ajax request to be re-attempted later, in hopes that the next time, it will succeed.
}, 3500);
return;
}
dynamic.replace(transport.responseText);
positionTooltip(element, tooltip);
},
onFailure: function(transport) {
timeouts.clear(url);
if (dynamic.parentNode) {// <- IE7 throws an exception if this check isn't included
dynamic.replace('<div class="tooltip-wrap">Error occured while trying to retrieve information. Try again later.</div>');
setTimeout(function() {
tooltip.remove(); //Remove the tooltip. This will allow the ajax request to be re-attempted later, in hopes that the next time, it will succeed.
}, 3500);
}
},
onComplete: function() {
timeouts.clear(url);
}
});
timeouts.add(function() {
request.options.onSuccess = null;
if (request.transport.abort) {//IE6 has no "abort()" method
request.transport.abort();
}
if (request.options.onFailure) {
request.options.onFailure(request.transport, request.json);
}
}, url);
}
positionTooltip(element, tooltip);
tooltipCounter++;
return tooltip;
};
var findAndRegisterTooltip = function(element) {
var o = self.options;
if (!o.content) {
var selector = '.' + o.baseClass + '[rel="' + o.getAjaxUrl(element) + '"]';
var tooltip = $$(selector)[0];
if (tooltip !== undefined && tooltip != null) {
element.setAttribute('tooltipID', tooltip.id);
positionTooltip(element, tooltip);
return tooltip;
}
}
return null;
};
var getTooltip = function(element, createTooltip) {
createTooltip = createTooltip || true;
var tooltip = null;
if (element.getAttribute('tooltipID') != null) {
tooltip = $(element.getAttribute('tooltipID'));
}
if (tooltip == null) {
tooltip = findAndRegisterTooltip(element);
if (tooltip == null && createTooltip) {
tooltip = createNewTooltip(element);
}
}
positionTooltip(element, tooltip);
return tooltip;
};
var showTooltip = function(event) {
var element = getElementFromEventOrDefault(event);
if (typeof element == 'undefined' || element == null)
return;
var tooltip = getTooltip(element);
if (!element.id) {
element.id = 'trigger-' + triggerCounter++;
}
var o = self.options;
if (element.hasClassName('dimLight')) {
return;
}
RJS.Timer.clear("tt", "tt");
RJS.Timer.add("tt", "tt", function() {
if (isMouseOverElement(element, RJS.Mouse)) {
if (self.options.hide === 'click') {
$(body).observe('click', hideTooltip)
}
activeTooltip.set(tooltip.id);
}
}, o.hoverIntentDelay);
};
var hideTooltip = function(event) {
RJS.Timer.clear("tt", "tt");
activeTooltip.unset();
};
var init = function(opts) {
Object.extend(self.options, opts);
var o = self.options;
if (o.element == null && o.selector != null) {// If no *specific* element is specified, use event delegation instead of subscribing to each element individually.
var c = $(o.context).observe(o.show, showTooltip);
if (o.hide != 'click') {
c.observe(o.hide, hideTooltip);
}
} else if (o.element != null) {
var c = $(o.element).observe(o.show, showTooltip);
if (o.hide != 'click') {
c.observe(o.hide, hideTooltip);
}
}
// Prefetch the template so CSS images are loaded in the background, making the UI load instantly when the user is shown a tooltip.
Event.observe(window, 'load', function() {
prefetchTemplate(o.tooltipTemplate, o.baseClass);
});
};
init(opts);
};
var prefetchTemplate = function(html, rootClass) {
prefetchTemplate.cache = prefetchTemplate.cache || {};
prefetchTemplate.cache[arguments] = prefetchTemplate.cache[arguments] || (function(html, rootClass) {
var prefetchTemplate = $(createElement(html));
prefetchTemplate.addClassName('prefetch');
prefetchTemplate.addClassName(rootClass);
prefetchTemplate.style.visibility = 'hidden';
prefetchTemplate.style.display = 'block';
$(body).insert(prefetchTemplate);
})(html, rootClass);
};
var isMouseOverElement = function(e, m) {
return RJS.isMouseOverElement(e, m);
};
var createElement = function(html) {
createElement.cache = createElement.cache || {};
createElement.cache[html] = createElement.cache[html] || (function(html) {
var temp = document.createElement('div');
temp.innerHTML = html;
if (temp.childNodes.length === 1)
return temp.firstChild;
return temp.childNodes;
})(html);
return createElement.cache[html].cloneNode(true);
};
var unnamedInstancesCount = 0;
return {
init: function(options) {
var tt = new Tooltip(options);
if (tt.options != null && tt.options !== '' && tt.options.instanceName !== '') {
instances[tt.options.instanceName] = tt;
} else {
tt.options.instanceName = 'unnamed-' + unnamedInstancesCount;
instances[tt.options.instanceName] = tt;
unnamedInstancesCount++;
}
return tt;
},
getInstance: function(name) {
if (name != null && name != '') {
return instances[name];
}
return null;
},
hideAll: function() {
for (var name in instances) {
var i = instances[name];
i.hideActive();
}
}
};
})();

/*************************** rjs.user.js ***************************/
;(function($) {
var RJS = window.RJS || (window.RJS = {});
var User = function() {
var self = this;
self.userInfoLoaded = false;
self.entitlements = null;
self.signedIn = false;
var topHeader,
loginColorboxOptions = $.fn.colorbox.standardOptions.login,
userMsgColorboxOptions = $.fn.colorbox.standardOptions.userMessage;
self.add_UserLoggedIn = function(userLoggedInHandler) {
RJS.Event.bind("user.loggedIn", userLoggedInHandler);
};
self.add_UserLoggingIn = function(userLoggingInHandler) {
RJS.Event.bind("user.loggingIn", userLoggingInHandler);
};
self.add_UserInfoLoaded = function(userInfoLoadedHandler) {
RJS.Event.bind("user.infoLoaded", userInfoLoadedHandler);
if (self.userInfoLoaded) {
userInfoLoadedHandler();
}
};
self.isSignedIn = function() {
if (!self.signedIn || !self.userInfoLoaded)
return false;
if (self.signedIn && new Date() > self.signInExpiresDate) {
self.signedIn = false;
self.userInfoLoaded = false;
//self.reloadUserInfo();
topHeader.find("h1.page-title").next().find(".last").text("Signing out...");
return false;
}
if (self.signedIn)
return true;
return false;
};
var updateUserContent = function(json, request, header) {
var content = $(json.userInfoDockHtml);
content.hide();
$("ul.userInfo").remove();
header.after(content);
content.fadeIn(50);
self.userInfoLoaded = true;
var href = window.location.href;
if (/\/user$/.match(href) || href.indexOf("/user/") > -1) {
content.find("a:contains('Join')").addClass("active");
} else if (/\/account\/playlist$/.match(href) || href.indexOf("/account/playlist") > -1) {
content.find("a:contains('My Playlist')").addClass("active");
} else if (/\/account\/rentals$/.match(href) || href.indexOf("/account/rentals") > -1) {
content.find("a:contains('My Active Rentals')").addClass("active");
} else if (/\/account$/.match(href) || href.indexOf("/account/") > -1) {
content.find("a:contains('My Profile')").addClass("active");
} else if (/\/help$/.match(href) || href.indexOf("/help/") > -1) {
content.find("a:contains('Help')").addClass("active");
}
$.extend(self, json);
if (self.signedIn) {
setTimeout(function() {
if (!self.isSignedIn()) {
self.reloadUserInfo();
}
}, self.signInExpires);
self.signInExpiresDate = new Date(self.signInExpires);
}
if (self.message && top == window && RJS.Cookie.get("hideMessage") !== "true") {
var c = {};
$.extend(c, userMsgColorboxOptions);
c.href = URLUtil.userMessage(self.message.template) + "?msgID=" + self.message.id;
if (self.message.template.indexOf('AccountInfoOK') > -1) {
c.title = "While you were away... we verified your account!";
} else if (self.message.template.indexOf('ConfirmWirelessNumber') > -1) {
c.title = "Sorry, we had a bit of an issue while you were away";
} else {
c.title = "We tried again but we still can't verify your account because...";
}
RJS.Cookie.set("hideMessage", "true", 999);
$.fn.colorbox(c);
}
setTimeout(function() {
self.applyUserSettingsToAssets();
}, 1);
RJS.Event.trigger("user.infoLoaded");
};
self.reloadUserInfo = function(returnUrl) {
self.userInfoLoaded = false;
try {
$.fn.colorbox.close();
} catch (e) { }
var result = RJS.Event.trigger("user.loggingIn", returnUrl);
if (!result) {
return;// If handlers of this event returns false, don't continue loading stuff.
}
var url = URLUtil.resolveUrl("~/h/userinfo");
var header = null;
if (topHeader.length > 0) {
header = topHeader.find("h1.page-title");
$("ul.userInfo").remove();
}
var request = $.ajax({
url: url,
dataType: "json",
cache: false,
success: function(json) {
if (header == null) {
header = topHeader.find("h1.page-title");
}
updateUserContent(json, request, header);
RJS.Event.trigger("user.loggedIn", [returnUrl]);
},
error: function() {
window.console && console.log("Error! ", arguments);
}
});
if (topHeader.length > 0) {
header = topHeader.find("h1.page-title");
header.after('<ul class="util fltrght userInfo"><li class="last" style="text-decoration: underline">Signing in...</li></ul>');
setTimeout(function() {// Handle login timeouts
if (header.text().indexOf("Signing in...") > -1) {
location.reload(true);
}
}, 30000);
}
};
var loadUserInfo = function() {
var url = URLUtil.resolveUrl("~/h/userinfo");
var header = null;
var request = $.ajax({
url: url,
dataType: "json",
cache: false,
success: function(json) {
if (header == null) {
header = topHeader.find("h1.page-title");
}
updateUserContent(json, request, header);
},
error: function() {
self.userInfoLoaded = true;
self.signedIn = false;
window.console && console.log("Error! ", arguments);
RJS.Event.trigger("user.infoLoaded");
}
});
if (topHeader.length > 0) {
header = topHeader.find("h1.page-title");
}
};
self.signOut = function() {
var oldUserInfo = $("ul.userInfo");
$.ajax({
url: URLUtil.resolveUrl("~/h/userinfo/true"),
type: "POST",
timeout: 10000,
complete: function() {
window.location = URLUtil.resolveUrl("~/");
}
});
return false;
};
self.signIn = function(args) {
var settings = { returnUrl: null, user: null, loginTitle: null, height: loginColorboxOptions.height, width: loginColorboxOptions.width };
$.extend(settings, args);
settings.returnUrl = settings.returnUrl == null ? "" : settings.returnUrl.toString();
var c = {};
$.extend(c, loginColorboxOptions);
if ($.trim(settings.title).length > 0) {
c.title = settings.title;
}
if ($.trim(settings.returnUrl).length > 0) {
c.href = URLUtil.resolveUrl("~/h/login?ReturnUrl=" + escape(settings.returnUrl));
}
if ($.trim(settings.user).length > 0) {
c.href = RJS.appendQueryParam(c.href, "user", settings.user);
}
if ($.trim(settings.loginTitle).length > 0) {
c.href = RJS.appendQueryParam(c.href, "loginTitleType", settings.loginTitle);
}
c.title = null;// Title is set to null, since we never want the login colorbox to display a title but callers can potentially attempt to set one.
c.height = settings.height;
c.width = settings.width;
$.fn.colorbox(c);
};
self.lockLinks = function(aTags) {
var $links = $(aTags);
$links.attr("originalHref", function() {
if ($(this).attr("originalHref")) {
return $(this).attr("originalHref");
}
return this.href;
});
$links.colorbox(loginColorboxOptions);
};
self.unlockLinks = function(aTags) {
var $links = $(aTags);
$links.attr("href", function() {
if ($(this).attr("originalHref")) {
return $(this).attr("originalHref");
}
return this.href;
});
};
self.applyUserSettingsToAssets = function() {
if (self.userInfoLoaded !== true) return;
$("div.entitlementTT").remove(); // Remove the lock icon tooltips, so that they'll be recalculated after user settings are applied.
$("li.media-item:has(a.hover-icon)").each(function() {
var $this = $(this);
var entitlementCode = $this.attr("data-entitlement");
var hoverIcon = $this.find(".hover-icon");
// Null or empty entitlement, all users have access
var emptyEntitlement = (typeof entitlementCode === "undefined" || entitlementCode == null || entitlementCode === "" || entitlementCode === "00000000-0000-0000-0000-000000000000");
if (emptyEntitlement) {
hoverIcon.removeClass('locked').addClass('play');
return true;
}
var entitlements = RJS.User.entitlements;
if (entitlements != null) {
for (var i = 0; i < entitlements.length; i++) {
if (entitlements[i] === entitlementCode) { //<- User has this specific entitlement
hoverIcon.removeClass('locked').addClass('play');
return true;
}
}
}
return true;
});
$("div.entitlement").each(function() {
var $this = $(this);
var entitlementCode = $this.attr("rel");
var link = $this.closest("li").find(".thumbAlt,.thumb").find("a").get(0);
var links = $this.closest("li").find("a").filter(function() {
return this.href === link.href;
});
if ($this.attr("tooltipid")) {
$("#" + $this.attr("tooltipid")).remove();
$this.removeAttr("tooltipid");
}
// Null or empty entitlement, all users have access
var emptyEntitlement = (typeof entitlementCode === "undefined" || entitlementCode == null || entitlementCode === "" || entitlementCode === "00000000-0000-0000-0000-000000000000");
if (emptyEntitlement) {
$this.remove();
RJS.User.unlockLinks(links);
return true;
}
var entitlements = RJS.User.entitlements;
if (entitlements != null) {
for (var i = 0; i < entitlements.length; i++) {
if (entitlements[i] === entitlementCode) { //<- User has this specific entitlement
$this.remove();
RJS.User.unlockLinks(links);
return true;
}
}
}
$this.removeClass("entitled");
});
if (self.signedIn === false) return;
if ("rentals" in RJS.User && RJS.User.rentals.length > 0) {
$("a.details").each(function() {
var $this = $(this);
var aid = this.rel;
if (hasRental(aid)) {
this.href = this.rev;
$this.text("Watch").removeClass('details').addClass('watch');
$this.closest("tr").children().eq(0).find("a").attr("href", this.rev);
}
});
$("p.price, div.price").each(function() {
var $this = $(this);
var aid = $this.attr("rel");
if (hasRental(aid)) {
$this.text("Rented").addClass('rented');
var rev = $this.attr("rev");
$this.closest(".video").find("a:not(.favorite)").attr("href", rev);
}
});
var buyButton = $(".rent-it", "#bdy");
if (buyButton.length > 0) {
var aid = buyButton.attr("rel");
if (hasRental(aid)) {
buyButton.text("Watch Now").attr("href", buyButton.attr("rev"));
}
if (buyButton.is(":hidden")) {
buyButton.show();
}
}
$('li.media-item').each(function() {
var $this = $(this),
aid = $this.data('id');
if (hasRental(aid)) {
$this.find('a[href]').each(function() {
if (this.href.indexOf('/rentals/detail/') > 0) {
this.href = this.href.replace('/rentals/detail/', '/rentals/watch/');
}
});
}
});
$(".rentalAssetCount").text(" (" + RJS.User.rentals.length + ")");
}
if (RJS.User.favorites.length > 0) {
$(".playlistAssetCount").text(" (" + RJS.User.favorites.length + ")");
}
$("a.favorite:not('.added')").each(function() {
var id = this.rel;
if (self.favorites !== undefined && self.favorites.length !== 0) {
for (var i = 0; i < self.favorites.length; i++) {
if (self.favorites[i] === id) {
$(this).removeClass("add").addClass("added").removeAttr("tooltipid");
return true;
}
}
}
});
};
function hasRental(assetID) {
if (!assetID || !("rentals" in RJS.User && RJS.User.rentals.length > 0)) {
return false;
}
for (var i = 0; i < RJS.User.rentals.length; i++) {
if (RJS.User.rentals[i] == assetID)
return true;
}
return false;
}
$(function() {
topHeader = $("#header");
loadUserInfo();
$("a.asyncSignout", topHeader.get(0)).live('click', function signoutClick(e) {
if (e.button != 0) return true;
self.signOut();
$(this).attr("href", "javascript:void(0);").css("text-decoration", "underline").text("Signing Out...");
e.preventDefault();
return false;
});
$("a.requireLoggedIn").live('click', function requireLoggedInClick(e) {
if (e.button == 0 && !self.userInfoLoaded) {
return false;
}
if (e.button == 0 && !self.signedIn) {
if (!self.userInfoLoaded) {
e.preventDefault();
return false;
}
self.signIn({ returnUrl: this.href, height: 355, loginTitle: $(this).attr('data-login-title') });
e.preventDefault();
return false;
}
});
$("a.loginLink").live('click', function loginLinkClick(e) {
if (e.button == 0 && !self.signedIn) {
self.signIn();
e.preventDefault();
return false;
}
});
if (window.location.hash && location.hash.match(/^#login(&|$)/gi)) {
window.console && console.log(window.location.hash);
var pairs = location.hash.substr(1).split('&');
window.console && console.log(pairs);
for (var i = 0; i < pairs.length; i++) {
if (pairs[i].indexOf('=') > -1) {
var pair = pairs[i].split('=');
window.console && console.log(pair);
if (pair[0] === 'user') {
self.signIn({ user: pair[1] });
}
}
}
}
});
}
var user = new User();
RJS.User = user;
})(jQuery);

/*************************** rjs.validate.js ***************************/
/// <reference path="http://jqueryjs.googlecode.com/files/jquery-1.3.2-vsdoc2.js" />
RJS.Validate = new function() {
var self = this;
var $ = window.jQuery;
var wrappedFlag = 'wrapped';
var validationError = 'validation-error';
var validationHtml = $('<div class="' + validationError + '"></div>');
var validationSelector = '.' + validationError;
function abortRequests(requests) {
while (requests.length > 0) {
var req = requests.pop();
req.abort();
}
};
// We explicitly declare all validation, so remove class rule settings from the jQuery validator so it doesn't conflict with our CSS naming
if ('classRuleSettings' in $.validator) {
$.validator.classRuleSettings = { };
}
function containsError(valWrapper, errorText) {
var contains = false;
valWrapper.find(settings.errorElement + "." + settings.errorClass).each(function() {
var text = $(this).text();
if (text === errorText) {
contains = true;
return false;
}
});
return contains;
}
self.standardOptions = {
ignore: ".ignore",
errorElement: "p",
errorClass: "invalid",
// set these events to false to prevent validating automatically as a user fixes invalid fields. Validation only happens on submission.
onkeyup: false,
onfocusout: false,
onfocusin: false,
onclick:false,
rules: {},
messages: {},
invalidHandler: function(form, validator) {
var errors = $('.errors');
if (errors.length > 0) {
errors.show();
}
$('html, body').animate({ scrollTop: 0/*errors.offset().top*/ }, "fast");
$('input[type=submit]').removeAttr('disabled');
},
errorPlacement: function(error, element, debug) {
if (trim(error.text()) === "") return;
var elemParent = $(element).parent();
var errorContainer = elemParent.find(validationSelector);
if (errorContainer.length > 0 && errorContainer.text().indexOf(error.text()) > -1) {
return;
}
if (errorContainer.length === 0) {
errorContainer = validationHtml.clone();
elemParent.append(errorContainer);
}
errorContainer.append(error);
if (document.activeElement && element[0].id === document.activeElement.id) {
element.focus();
}
},
onHideError: function(error) {
var err = $(error);
var len = err.parent().find("p.invalid:visible").length;
if (len === 0) {
err.parent().remove();
}
},
unhighlight: unhighlight
};
if (self.standardOptions.debug) {
window.console && window.console.warn && console.warn('jQuery.validate debugging is enabled. Some forms may not submit themselves until debugging is turned off.');
}
// Our code simplifies errors message registration by creating a general-purpose "invalid" for all messages except required ones.
// This method assigns the "invalid" message to a message property for each rule applied to that element.
function setMessagesForInvalids(o) {
if ('messages' in o) {
for(var i in o.messages) {
var m = o.messages[i];
if (typeof m === 'object' && 'invalid' in m) {
for(var j in o.rules) {
for(var k in o.rules[j]) {
if (k !== 'required' && !(k in o.messages[i])) {
o.messages[i][k] = m.invalid;
}
}
}
}
}
}
}
function unhighlight(element, errorClass) {
if ($(element).hasClass('ignore')) {
window.console && console.log('ignoring: ', element);
return;
}
if (self.getValidator().numberOfInvalids() === 0) {// If nothing on the page is invalid anymore, hide the validation summary at the top of the form
$(".errors").hide();
}
var valWrap = $(element).parent().find(validationSelector);
if (valWrap.length === 0)
return;
valWrap.remove();
$(element).removeClass(errorClass);
}
var validator;
var settings;
self.getValidator = function() { return validator; };
// If this method is called more than once, new options are added to the existing ones.
self.register = function register(form, options) {
// The "form" argument is optional (only the options argument is required).
if (typeof options === "undefined" && typeof form !== "string" && typeof form.jquery !== "string") {
options = form;
form = $("form");
} else {
if (arguments.length > 2 || arguments.length === 0) {
throw { name: "InvalidArgumentCountException", message: "RJS.Validator.register() requires at least 1 argument and no more than 2.", toString: function() { return this.name + ": " + this.message; } };
}
}
// If the validator has not been initialized, initialize it
if (typeof validator === "undefined") {
var temp = {};
$.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
phone_number = phone_number.replace("(", "");
phone_number = phone_number.replace(")", "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})$/);
}, "Please enter a valid Rogers wireless phone number.");
// Addon method for validating postal codes. Valid
// formats are (X1X 1X1) or (X1X1X1) or (X1X-1X1).
$.validator.addMethod("postalCode", function(value) {
value = value.replace(/\s/g, '');
value = value.replace(/[^a-zA-Z 0-9]+/g, '');
return value.match(/^[a-zA-Z][0-9][a-zA-Z][^A-z0-9]*[0-9][a-zA-Z][0-9]$/);
}, 'Please enter a valid postal code');
$.validator.addMethod("noSpecialChars", function(value, element) {
return this.optional(element) || /^[a-z0-9]+$/i.test(value);
}, "Only letters and numbers are allowed.");
setMessagesForInvalids(options);
$.extend(temp, self.standardOptions);
$.extend(temp, options);
validator = $(form).validate(temp);
settings = validator.settings;
// If there is an update panel on the page, validate when the UpdatePanel submits the form
if (typeof Sys !== "undefined"
&& typeof Sys.WebForms !== "undefined"
&& typeof Sys.WebForms.PageRequestManager !== "undefined") {
var prm = Sys.WebForms.PageRequestManager.getInstance();
// jQuery.validate doesn't trigger validation automatically within update panels. Manually trigger validation if conditions are met.
prm.add_initializeRequest(function(sender, args) {
if (validator.cancelSubmit || $(args.get_postBackElement()).hasClass("cancel") || $(args.get_postBackElement()).attr('type') === 'hidden') {
validator.cancelSubmit = true;
return true;
}
var isValid = validator.form();// calling .form() triggers the validation plugin to begin validating
if (validator.pendingRequest) {
window.console && console.log("pendingRequest: ", validator.pendingRequest);
isValid = false;
}
if (!isValid) {
args.set_cancel(true);
}
});
prm.add_endRequest(function(sender, args) {
validator.cancelSubmit = false;
});
}
}
var baseRules = settings.rules;
var baseMessages = settings.messages;
if (options.rules) {
$.extend(baseRules, options.rules);
}
if (options.messages) {
$.extend(baseMessages, options.messages);
}
$.extend(settings, options);
settings.rules = baseRules;
settings.messages = baseMessages;
return validator;
}
self.checkAvailability = function(ev, async) {
var data = ev.data;
var element = $(data.element);
var value = element.val();
var o = settings;
var fieldNameTitleCase = data.fieldName.substring(0, 1).toUpperCase() + data.fieldName.substring(1);
async = typeof async !== "undefined" ? async : true;
// Only check availability if the value is valid to begin with
if (!data.isValid(value)) {
var invalidNode = $("p." + o.errorClass + ":contains(' is not available.')");
var parent = invalidNode.parent();
invalidNode.remove();
if (parent.length !== 0 && parent.find("p." + o.errorClass).length === 0) {
unhighlight(element.get(0), o.errorClass);
}
var congrats = $(data.congratsSelector);
congrats.empty();
return true;
}
var ajaxParams = {
dataType: "json",
url: data.url,
type: "POST",
data: {},
async: async,
success: function(available) {
var congrats = $(data.congratsSelector);
if (available) {
congrats.addClass("valid").html("Yes, <span class='avail'> " + value + "</span> is available.").show();
element.removeClass(o.errorClass);
unhighlight(element.get(0), o.errorClass);
return true;
} else {
congrats.addClass("invalid").html("Sorry,<span> " + value + "</span> is not available. Please choose another " + data.fieldName + ".").show();
element.addClass(o.errorClass);
o.errorPlacement($('<p class="' + o.errorClass + '">' + fieldNameTitleCase + ' is not available.</p>'), element);
return false;
}
}
};
ajaxParams.data[data.fieldName] = value;
var f = self.checkAvailability[element.attr("id")];
if (!f) {
f = {};
self.checkAvailability[element.attr("id")] = f;
}
if (!f.requests) {
f.requests = [];
}
abortRequests(f.requests);
f.requests.push($.ajax(ajaxParams));
};
};

/*************************** rjs.video.js ***************************/
//builds the contents of the video page, handles playlist
RJS.Video = function (id, handler, callback) {
var filters = {};
//variable to track the item count globally since this value is only returned on the first call
var count = null;
//variable to track if the event came from a filter click or a pager click globally
var requestFromFilter = false;
var setHandler = function (url) {
var parts = URLUtil.resolveUrl(url).split('?');
if (parts.length == 2) {
handler = parts[0];
filters = parts[1].toQueryParams();
}
}
setHandler(handler)
if ($(id) == null) {
return;
}
var element = $(id),
outer = element.up('div.content'),
pager, pagerRoot = (outer ? outer.down('ol.pager-root') : null),
assetsPerPage = parseInt(filters["max"]),
pageNo = 0,
loading = (outer ? outer.down('.content_loading') : null),
emptyContent = (outer ? outer.down('.content_empty') : null),
errorContent = (outer ? outer.down('.content_error') : null),
loadingAjax = false;
var findAll = function (object, f) {
return $H(object).inject(new Hash(), function (result, pair) {
if (f(pair)) result.set(pair.key, pair.value);
return result;
});
};
//ajax requester
var requestMedia = function (success) {
loadingAjax = true;
element.update();
var requestListing = function (params) {
var hash = $H(filters).update(params);
if (loading) {
setTimeout(function () {
if (loadingAjax) {
loading.setStyle({ display: "block" });
}
}, 200);
}
if (errorContent) {
errorContent.setStyle({ display: "none" });
}
if (emptyContent) {
emptyContent.setStyle({ display: "none" });
}
new Ajax.Request(handler, {
method: 'GET', parameters: findAll(hash, function (pair) { return pair.value && pair.value != ""; }),
onSuccess: success,
onFailure: failure,
onException: exception
});
};
var failure = function () {
loadingAjax = false;
if (loading) {
loading.setStyle({ display: "none" });
}
if (errorContent) {
errorContent.setStyle({ display: "block" });
}
window.console && console.log('failure');
};
var exception = function (a, b) {
loadingAjax = false;
if (loading) {
loading.setStyle({ display: "none" });
}
if (errorContent) {
errorContent.setStyle({ display: "block" });
}
if (window.console && window.console.error) window.console.error("exception in RJS.Video %o", b);
else if (window.console && window.console.log) window.console.log(a, b);
else if (window.JSON && JSON.stringify) throw (JSON.stringify({ argA: a, argB: b }));
else throw { argA: a, argB: b };
};
if (!isNaN(assetsPerPage)) requestListing({ offset: (pageNo * assetsPerPage) });
else requestListing({});
};
var buildPager = function (pageCount) {
if (isNaN(pageCount)) return;
if (!pager) {
if (!pageCount) return;
pager = RJS.TBPager(id, pagerRoot, { totalPages: pageCount });
}
else pager.setTotalPages(pageCount, requestFromFilter);
};
var buildFilter = function (type) {
var value = filters[type];
var filterValid = false;
var defaultValue;
outer.select("a[rel=" + type + "]").each(function (n, i) {
if (i == 0) defaultValue = n.rev;
if (n.rev == value) filterValid = true;
n.observe("click", function () { document.fire('Video#' + id + ':filter', { type: n.rel, value: n.rev }); });
});
if (!filterValid) value = filters[type] = defaultValue;
setActive(type, value);
};
var destroyFilter = function (type) {
outer.select("a[rel=" + type + "]").each(function (n, i) {
n.stopObserving("click");
});
};
var buildFilterDDL = function (type) {
outer.select("select." + type).each(function (n, i) {
n.observe("change", function () { if (n.getValue() != 'do nothing') document.fire('Video#' + id + ':filter', { type: type, value: n.getValue() }); });
});
};
var destroyFilterDDL = function (type) {
outer.select("select." + type).each(function (n, i) {
n.stopObserving("change");
});
};
var setActive = function (type, value) {
outer.select("a[rel=" + type + "]").each(function (n, i) {
if (n.rev == value) n.addClassName("active"); else n.removeClassName("active");
});
};
//build the page elements based on the ajax response
var gotListing = function (response) {
loadingAjax = false;
if (loading) {
loading.setStyle({ display: "none" });
}
var json = response.responseJSON;
if (json) {
if (emptyContent && json.count == 0) {
emptyContent.setStyle({ display: "block" });
} else if (emptyContent) {
emptyContent.setStyle({ display: "none" });
}
if (json.assets)
buildFullList(json.assets, json.type);
if (json.channels)
buildFullList(json.channels);
if (json.comments)
buildFullList(json.comments);
if (json.matchAssets)
buildFullList(json.matchAssets);
if (json.groups)
buildFullList(json.groups);
if (count == null)
count = json.count;
if (pagerRoot) buildPager(Math.ceil(count / assetsPerPage));
var $ = jQuery;
RJS.User.applyUserSettingsToAssets();
if (callback) callback(json);
} else window.console && console.log("Got no JSON response, did we use application/json?");
};
var listBuilder = function () {
var getTemplateName = function (ri, type) {
if (typeof type !== 'undefined' && jQuery.isArray(ri)) {
if (RJS.Templates[type] && RJS.Templates[type].settings && RJS.Templates[type].settings.isForArray)
return type;
var template = filters["templates"];
if (template && template.settings && template.settings.isForArray) {
return template;
} else {
return null;
}
}
if (ri && ri.json && ri.json.type) {
return ri.json.type;
}
return filters["template"];
}
return RJS.Repeater({ getTemplateName: getTemplateName });
} ()
//build the list of asset of the currently selected AssetGroup
var buildFullList = function (assets, type) {
if (!assets) {
window.console && console.log('No assets!')
return;
}
element.update(listBuilder.buildString(assets, type));
//rewireTooltips(element);
};
document.observe('Pager:pageClick', function (evt) {
if (evt.memo.id == id) {
if (evt.memo.page == 0)
pageNo = 0;
else
pageNo = evt.memo.page - 1;
requestFromFilter = false;
requestMedia(gotListing)
}
});
document.observe('Video#' + id + ':filter', function (evt) {
filters[evt.memo.type] = evt.memo.value;
setActive(evt.memo.type, evt.memo.value);
//set offset/pageNo to 0 if filter is clicked
pageNo = 0;
count = null;
requestFromFilter = true;
requestMedia(gotListing);
});
if (outer) {
buildFilter("filter");
buildFilter("sort");
buildFilter("layout");
buildFilter("currentRun");
buildFilterDDL("season");
buildFilterDDL("language");
buildFilterDDL("sort");
buildFilterDDL("team");
}
//requestMedia(gotListing);
function destroy() {
document.stopObserving('Pager:pageClick');
document.stopObserving('Video#' + id + ':filter');
destroyFilter("filter");
destroyFilter("sort");
destroyFilter("layout");
destroyFilter("currentRun");
destroyFilterDDL("season");
destroyFilterDDL("language");
destroyFilterDDL("sort");
destroyFilterDDL("team");
}
return { setHandler: function (url) { setHandler(url); requestMedia(gotListing); }, load: function () { requestMedia(gotListing); }, destroy: destroy };
}

/*************************** rjs.welcome.js ***************************/
/// <reference path="http://jqueryjs.googlecode.com/files/jquery-1.3.2-vsdoc2.js" />
; (function($) {
RJS.Welcome = function(showSurvey) {
var c = RJS.Cookie,
surveyed = "Surveyed",
href = location.href;
var host = location.host;
var parts = host.split('.');
if (parts.length > 1) {
host = parts[parts.length - 2] + "." + parts[parts.length - 1];
}
if (showSurvey && (c.get(surveyed) !== "yes" && href.indexOf("/h/") === -1 && href.indexOf("/handlers/") === -1 && href.indexOf("/user") === -1 && top.location == location) && href.indexOf("/login") === -1 || getQueryString("showSurvey") === "true") {
$(function() {
$colorbox = $("#colorbox");
$("<a>Survey Element</a>").colorbox({
href: URLUtil.resolveUrl("~/h/survey"),
title: "Help us improve your viewing experience by taking a brief survey!",
height: 360,
width: 491,
open: true,
scrolling: false,
iframe: true,
onLoad: function() {
$colorbox.addClass("survey");
},
onCleanup: function() {
setTimeout(function() { $colorbox.removeClass("survey"); }, 1);
}
});
});
c.set(surveyed, "yes", new Date(9999, 0, 1), host);
}
}
})(jQuery);

/*************************** thickbox.js ***************************/
/*
* Thickbox 3.1 - One Box To Rule Them All.
* By Cody Lindley (http://www.codylindley.com)
* Copyright (c) 2007 cody lindley
* Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
var tb_pathToImage = URLUtil.resolveUrl("~/i/ajax-loader.gif");
/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/
imgLoader = new Image(); // preload image
imgLoader.src = tb_pathToImage;
//on page load call tb_init
jQuery().ready(function() {
tb_init('a.thickbox, area.thickbox, input.thickbox'); //pass where to apply thickbox
});
//add thickbox to href & area elements that have a class of .thickbox
function tb_init(selector) {
jQuery(selector).live('click', function(e) {
if (e.button === 0) {
var t = this.title || this.name || null;
var a = this.href || this.alt;
var g = this.rel || false;
tb_show(t, a, g);
jQuery("#TB_window").show();
this.blur();
return false;
}
});
}
var tb_isVisible = false;
function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link
if (tb_isVisible === true) return;
tb_isVisible = true;
try {
var queryString = url.replace(/^[^\?]+\??/, '');
var params = tb_parseQuery(queryString);
if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
jQuery("body", "html").css({ height: "100%", width: "100%" });
jQuery("html").css("overflow", "hidden");
if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
jQuery("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'" + (typeof params['class'] !== "undefined" ? " class='" + params['class'] + "'" : "") + "></div>");
if (params['unclosable'] !== 'true') { jQuery("#TB_overlay").click(tb_remove); }
}
} else {//all others
if (document.getElementById("TB_overlay") === null) {
jQuery("body").append("<div id='TB_overlay'></div><div id='TB_window'" + (typeof params['class'] !== "undefined" ? " class='" + params['class'] + "'" : "") + ">");
jQuery("#TB_window").append("<div id='TB_Shadow_t'></div><div id='TB_Shadow_b'></div><div id='TB_Shadow_r'></div><div id='TB_Shadow_l'></div><div id='TB_Shadow_tl'></div><div id='TB_Shadow_tr'></div><div id='TB_Shadow_bl'></div><div id='TB_Shadow_br'></div>");
if (params['unclosable'] !== 'true') { jQuery("#TB_overlay").click(tb_remove); }
}
}
if (tb_detectMacXFF()) {
jQuery("#TB_overlay").addClass("TB_overlayMacFFBGHack"); //use png overlay so hide flash
} else {
jQuery("#TB_overlay").addClass("TB_overlayBG"); //use background and opacity
}
if (caption === null) { caption = ""; }
jQuery("body").append("<div id='TB_load'><img src='" + imgLoader.src + "' /></div>"); //add loader to the page
jQuery('#TB_load').show(); //show loader
var baseURL;
if (url.indexOf("?") !== -1) { //ff there is a query string involved
baseURL = url.substr(0, url.indexOf("?"));
} else {
baseURL = url;
}
var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
var urlType = baseURL.toLowerCase().match(urlString);
if (urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp') {//code to show images
TB_PrevCaption = "";
TB_PrevURL = "";
TB_PrevHTML = "";
TB_NextCaption = "";
TB_NextURL = "";
TB_NextHTML = "";
TB_imageCount = "";
TB_FoundURL = false;
if (imageGroup) {
TB_TempArray = jQuery("a[@rel=" + imageGroup + "]").get();
for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
if (!(TB_TempArray[TB_Counter].href == url)) {
if (TB_FoundURL) {
TB_NextCaption = TB_TempArray[TB_Counter].title;
TB_NextURL = TB_TempArray[TB_Counter].href;
TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
} else {
TB_PrevCaption = TB_TempArray[TB_Counter].title;
TB_PrevURL = TB_TempArray[TB_Counter].href;
TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
}
} else {
TB_FoundURL = true;
TB_imageCount = "Image " + (TB_Counter + 1) + " of " + (TB_TempArray.length);
}
}
}
imgPreloader = new Image();
imgPreloader.onload = function() {
imgPreloader.onload = null;
// Resizing large images - orginal by Christian Montoya edited by me.
var pagesize = tb_getPageSize();
var x = pagesize[0] - 150;
var y = pagesize[1] - 150;
var imageWidth = imgPreloader.width;
var imageHeight = imgPreloader.height;
if (imageWidth > x) {
imageHeight = imageHeight * (x / imageWidth);
imageWidth = x;
if (imageHeight > y) {
imageWidth = imageWidth * (y / imageHeight);
imageHeight = y;
}
} else if (imageHeight > y) {
imageWidth = imageWidth * (y / imageHeight);
imageHeight = y;
if (imageWidth > x) {
imageHeight = imageHeight * (x / imageWidth);
imageWidth = x;
}
}
// End Resizing
TB_WIDTH = imageWidth + 30;
TB_HEIGHT = imageHeight + 60;
jQuery("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='" + url + "' width='" + imageWidth + "' height='" + imageHeight + "' alt='" + caption + "'/></a>" + "<div id='TB_caption'>" + caption + "<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'></a></div>");
if (params['unclosable'] !== 'true') { jQuery("#TB_closeWindowButton").click(tb_remove); }
if (!(TB_PrevHTML === "")) {
function goPrev() {
if (jQuery(document).unbind("click", goPrev)) { jQuery(document).unbind("click", goPrev); }
jQuery("#TB_window").remove();
jQuery("body").append("<div id='TB_window'></div>");
tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
return false;
}
jQuery("#TB_prev").click(goPrev);
}
if (!(TB_NextHTML === "")) {
function goNext() {
jQuery("#TB_window").remove();
jQuery("body").append("<div id='TB_window'></div>");
tb_show(TB_NextCaption, TB_NextURL, imageGroup);
return false;
}
jQuery("#TB_next").click(goNext);
}
document.onkeydown = function(e) {
if (e == null) { // ie
keycode = event.keyCode;
} else { // mozilla
keycode = e.which;
}
if (keycode == 27) { // close
if (params['unclosable'] !== 'true') { tb_remove(); }
} else if (keycode == 190) { // display previous image
if (!(TB_NextHTML == "")) {
document.onkeydown = "";
goNext();
}
} else if (keycode == 188) { // display next image
if (!(TB_PrevHTML == "")) {
document.onkeydown = "";
goPrev();
}
}
};
tb_position();
jQuery("#TB_load").remove();
if (params['unclosable'] !== 'true') { jQuery("#TB_ImageOff").click(tb_remove); }
jQuery("#TB_window").css({ display: "block" }); //for safari using css instead of show
};
imgPreloader.src = url;
} else {//code to show html
TB_WIDTH = (params['width'] * 1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
TB_HEIGHT = (params['height'] * 1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
ajaxContentW = TB_WIDTH - 30;
ajaxContentH = TB_HEIGHT - 45;
if (url.indexOf('TB_iframe') != -1) {// either iframe or ajax window
urlNoQuery = url.split('TB_');
jQuery("#TB_iframeContent").remove();
if (params['modal'] != "true") {//iframe no modal
jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>" + caption + "</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'></a></div></div><iframe frameborder='0' hspace='0' src='" + urlNoQuery[0] + "' id='TB_iframeContent' name='TB_iframeContent" + Math.round(Math.random() * 1000) + "' onload='tb_showIframe()' style='width:" + (ajaxContentW + 29) + "px;height:" + (ajaxContentH + 17) + "px;'> </iframe>");
} else {//iframe modal
jQuery("#TB_overlay").unbind();
jQuery("#TB_window").append("<iframe frameborder='0' hspace='0' src='" + urlNoQuery[0] + "' id='TB_iframeContent' name='TB_iframeContent" + Math.round(Math.random() * 1000) + "' onload='tb_showIframe()' style='width:" + (ajaxContentW + 29) + "px;height:" + (ajaxContentH + 17) + "px;'> </iframe>");
}
} else {// not an iframe, ajax
if (jQuery("#TB_window").css("display") != "block") {
if (params['modal'] != "true") {//ajax no modal
jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>" + caption + "</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'></a></div></div><div id='TB_ajaxContent' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px'></div>");
} else {//ajax modal
jQuery("#TB_overlay").unbind();
jQuery("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px;'></div>");
}
} else {//this means the window is already up, we are just loading new content via ajax
jQuery("#TB_ajaxContent")[0].style.width = ajaxContentW + "px";
jQuery("#TB_ajaxContent")[0].style.height = ajaxContentH + "px";
jQuery("#TB_ajaxContent")[0].scrollTop = 0;
jQuery("#TB_ajaxWindowTitle").html(caption);
}
}
if (params['unclosable'] !== 'true') { jQuery("#TB_closeWindowButton").click(tb_remove); }
if (url.indexOf('TB_inline') != -1) {
jQuery("#TB_ajaxContent").append(jQuery('#' + params['inlineId']).children());
jQuery("#TB_window").unload(function() {
jQuery('#' + params['inlineId']).append(jQuery("#TB_ajaxContent").children()); // move elements back when you're finished
});
tb_position();
jQuery("#TB_load").remove();
jQuery("#TB_window").css({ display: "block" });
} else if (url.indexOf('TB_iframe') != -1) {
tb_position();
if (jQuery.browser.safari) {//safari needs help because it will not fire iframe onload
jQuery("#TB_load").remove();
jQuery("#TB_window").css({ display: "block" });
}
} else {
jQuery("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()), function() {//to do a post change this load method
tb_position();
jQuery("#TB_load").remove();
tb_init("#TB_ajaxContent a.thickbox");
jQuery("#TB_window").css({ display: "block" });
});
}
}
if (!params['modal']) {
document.onkeyup = function(e) {
if (e == null) { // ie
keycode = event.keyCode;
} else { // mozilla
keycode = e.which;
}
if (keycode == 27) { // close
if (params['unclosable'] !== 'true') { tb_remove(); }
}
};
}
} catch (e) {
//nothing here
}
}
//helper functions below
function tb_showIframe() {
jQuery("#TB_load").remove();
jQuery("#TB_window").css({ display: "block" });
}
function tb_remove() {
tb_isVisible = false;
jQuery("#TB_imageOff").unbind("click");
jQuery("#TB_closeWindowButton").unbind("click");
jQuery("#TB_window").fadeOut("fast", function() { jQuery('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove(); });
jQuery("#TB_load").remove();
if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
jQuery("body", "html").css({ height: "auto", width: "auto" });
jQuery("html").css("overflow", "");
}
document.onkeydown = "";
document.onkeyup = "";
return false;
}
function tb_position() {
jQuery("#TB_window").css({ marginLeft: '-' + parseInt((TB_WIDTH / 2), 10) + 'px', width: TB_WIDTH + 'px' });
if (!(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
jQuery("#TB_window").css({ marginTop: '-' + parseInt((TB_HEIGHT / 2), 10) + 'px' });
}
}
function tb_parseQuery(query) {
var Params = {};
if (!query) { return Params; } // return empty object
var Pairs = query.split(/[;&]/);
for (var i = 0; i < Pairs.length; i++) {
var KeyVal = Pairs[i].split('=');
if (!KeyVal || KeyVal.length != 2) { continue; }
var key = unescape(KeyVal[0]);
var val = unescape(KeyVal[1]);
val = val.replace(/\+/g, ' ');
Params[key] = val;
}
return Params;
}
function tb_getPageSize() {
var de = document.documentElement;
var w = window.innerWidth || self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
var h = window.innerHeight || self.innerHeight || (de && de.clientHeight) || document.body.clientHeight;
arrayPageSize = [w, h];
return arrayPageSize;
}
function tb_detectMacXFF() {
var userAgent = navigator.userAgent.toLowerCase();
if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1) {
return true;
}
}

/*************************** tooltips.js ***************************/
jQuery(function($) {
jQuery('div.search-results').jTooltip({delegateSelector: 'div.media-screen'});
var swapTitleToTooltip = function(elem) {
if ($(elem).attr('title')) {
$(elem).attr("altTitle", $(elem).attr('title'));
$(elem).attr('title', '');
}
return $(elem).attr("altTitle");
};
var storeContext = document.getElementById("main");
if (storeContext && storeContext.className && storeContext.className.indexOf("store") > -1) {
RJS.Tooltip.init({
context: storeContext,
ignoreBottomContextBoundary: true,
ignoreTopContextBoundary: true,
ignoreLeftContextBoundary: true,
autoAdjust: true,
//baseClass: 'StoreBaseClass',
instanceName: 'Store',
selector: 'li.rental div.thumb a'
});
}
var storePlayerContext = RJS.fastSelector('div', 'end-playback');
if (storePlayerContext != undefined) {
RJS.Tooltip.init({
context: storePlayerContext,
ignoreBottomContextBoundary: true,
ignoreTopContextBoundary: true,
ignoreLeftContextBoundary: true,
autoAdjust: true,
//baseClass: 'StoreBaseClass',
instanceName: 'Store',
selector: 'li.rental div.thumb a'
});
}
var homeContext = $('#home-content .left').get(0);
if (homeContext !== undefined) {
var homeDefaults = {
context: homeContext,
ignoreBottomContextBoundary: true,
ignoreTopContextBoundary: true,
ignoreLeftContextBoundary: true,
adjustLeft: -20,
autoAdjust: true
};
RJS.Tooltip.init(
$.extend({}, homeDefaults, {
selector: 'div.thumb, div.thumbAlt',
adjustTop: 0,
instanceName: 'Main'
}));
RJS.Tooltip.init(
$.extend({}, homeDefaults, {
selector: 'a.ratingsInfo',
position: 'bottom',
nudgeLeft: -10,
adjustRight: -20,
adjustBottom: -20,
baseClass: 'ratingsInfo_hover',
instanceName: 'Ratings'
}));
RJS.Tooltip.init({// Code repeated in the "regular context"
selector: 'div.entitlement',
position: 'top',
direction: 'rightTopClass',
baseClass: 'info_hover entitlementTT',
content: function() {
if (RJS && RJS.User && RJS.User.isSignedIn())
return '<div class="tooltip-wrap">You need a Rogers subscription to watch this video.</div>';
return '<div class="tooltip-wrap">You need to sign in and may require a Rogers subscription to watch this video.</div>'
},
instanceName: 'entitlement'
});
}
var regularContext = $("#middle, #right:has(#landing,#browse_content,.genre)").get(0);
if (regularContext !== undefined) {
var regularContextOptions = {
context: regularContext,
ignoreBottomContextBoundary: true,
ignoreTopContextBoundary: true,
autoAdjust: true,
adjustLeft: -20
};
RJS.Tooltip.init(
$.extend({}, {
selector: 'div.thumb, div.thumbAlt, div.channel, a.channelsList, li.thumb',
adjustTop: 0,
instanceName: 'Main'
}, regularContextOptions));
RJS.Tooltip.init(
$.extend({}, {
selector: 'a.ratingsInfo',
nudgeLeft: -10,
adjustRight: -15,
adjustBottom: -20,
baseClass: 'ratingsInfo_hover',
instanceName: 'Ratings'
}, regularContextOptions));
RJS.Tooltip.init({// Code repeated in the "home context"
selector: 'div.entitlement',
position: 'top',
direction: 'rightTopClass',
baseClass: 'info_hover entitlementTT',
content: function() {
if (RJS && RJS.User && RJS.User.isSignedIn())
return 'You need a Rogers subscription to watch this video.';
return 'You need to sign in and may require a Rogers subscription to watch this video.'
},
instanceName: 'entitlement'
});
}
var infoAlt = RJS.fastSelector("a", "infoAlt");
if (infoAlt) {
RJS.Tooltip.init({
element: infoAlt,
position: 'top',
baseClass: 'infoAlt_hover',
direction: 'rightTopClass',
autoAdjust: true,
ignoreBottomContextBoundary: true,
ignoreTopContextBoundary: true,
adjustLeft: 0,
instanceName: 'infoAlt'
});
}
RJS.Tooltip.init({// Need a way to prevent this tooltip from using the whole page as its context...
selector: 'a.favorite',
position: 'top',
direction: 'rightTopClass',
content: function(elem) {
if (elem.className.indexOf('added') > -1) {
return '<div class="tooltip-wrap">This video is on your playlist. Click again to view and modify your playlist</div>';
} else {
return '<div class="tooltip-wrap">Add this video to your playlist</div>';
}
},
instanceName: 'AddedToFavorite',
hoverIntentDelay: 600
});
var verifyCustomerCtrl = document.getElementById('account');
if (verifyCustomerCtrl) {
RJS.Tooltip.init({
context: verifyCustomerCtrl,
selector: '.cbVerify',
position: 'top',
direction: 'rightTopClass',
content: '<div class="tooltip-wrap">This will verify the information you have entered.</div>',
instanceName: 'verify',
hoverIntentDelay: 600
});
RJS.Tooltip.init({
context: verifyCustomerCtrl,
selector: '.cbLater',
position: 'top',
direction: 'rightTopClass',
content: '<div class="tooltip-wrap">No problem, you can skip the verification for now.</div>',
instanceName: 'verifyLater',
hoverIntentDelay: 600
});
RJS.Tooltip.init({
selector: '.cbSendNow',
position: 'top',
direction: 'rightTopClass',
content: 'A text will be sent to the number you entered above.',
instanceName: 'sendNow',
hoverIntentDelay: 600
});
}
var highlights = jQuery("#matchHighlights");
if (highlights.length > 0) {
RJS.Tooltip.init({
selector: '.off',
baseClass: 'matchInfo_hover',
position: 'top',
direction: 'leftTopClass',
content: '<h3>Match Highlights</h3><p>Switch to ON to see the latest score and highlights. Spoiler alert!</p>',
instanceName: 'off',
hoverIntentDelay: 600
});
RJS.Tooltip.init({
selector: '.on',
baseClass: 'matchInfo_hover',
position: 'top',
direction: 'leftTopClass',
content: '<h3>Match Highlights</h3><p>Switch to OFF to see score and highlights as they unfold.</p>',
instanceName: 'off',
hoverIntentDelay: 600
});
RJS.Tooltip.init({
context: highlights.get(0),
baseClass: 'event_hover',
selector: '.eventType',
position: 'top',
direction: 'rightTopClass',
instanceName: 'matchEvent',
content: swapTitleToTooltip
});
}
var liveText = RJS.fastSelector("a", "liveText");
if (liveText) {
RJS.Tooltip.init({
element: liveText,
position: 'top',
direction: 'rightTopClass',
content: 'Text &#39;SAY&#39; &#43; your comment to 101010',
instanceName: 'sendNow',
hoverIntentDelay: 600
});
}
var rentalWatchPage = document.getElementById('rental-player');
if (rentalWatchPage) {
var rentalWatchContext = document.getElementById('detail-summary-wrap');
RJS.Tooltip.init({
context: rentalWatchContext,
selector: 'a.share',
position: 'top',
direction: 'rightTopClass',
content: '<div class="tooltip-wrap">Share this video.</div>',
instanceName: 'AddedShare',
hoverIntentDelay: 600
});
} else {
var share = RJS.fastSelector("a", "share");
if (share) {
RJS.Tooltip.init({
element: share,
position: 'top',
direction: 'rightTopClass',
content: '<div class="tooltip-wrap">Share this video.</div>',
instanceName: 'AddedShare',
hoverIntentDelay: 600
});
}
}
var titleInfo = RJS.fastSelector("a", "titleInfo");
if (titleInfo) {
RJS.Tooltip.init({
element: titleInfo,
baseClass: 'assetInfo_hover',
position: 'bottom',
direction: 'leftBottomClass',
nudgeTop: 20,
adjustLeft: -203,
instanceName: 'TitleInfo'
});
}
var assetInfoImg = RJS.fastSelector('a', 'assetInfoImg');
if (assetInfoImg) {
RJS.Tooltip.init({
element: assetInfoImg,
baseClass: 'assetInfo_hover',
position: 'bottom',
direction: 'leftBottomClass',
nudgeTop: 20,
adjustLeft: -208,
instanceName: 'AssetInfoImg'
});
}
RJS.Tooltip.init({
selector: 'a.FindbytitleInfo, div.FindbytitleInfo',
adjustLeft: -20,
adjustTop: 0,
instanceName: 'FindbytitleInfo'
});
var contentInfoOptions = {
autoAdjust: true,
baseClass: 'contentInfo_hover',
content: swapTitleToTooltip
};
RJS.Tooltip.init($.extend({}, { selector: 'a.contentInfo', instanceName: 'contentInfoHover' }, contentInfoOptions));
RJS.Tooltip.init($.extend({}, { selector: 'a.contentInfoLink', hide: 'click', instanceName: 'contentInfoHoverLink' }, contentInfoOptions));
});

/*************************** util.js ***************************/
//****************************************************************************
// Copyright (C) thePlatform for Media, Inc. All Rights Reserved.
//****************************************************************************
////// UTIL FUNCTIONS ////////////
// Gets Url Params
var urlParams = {};
(function() {
var e,
a = /\+/g,  // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function(s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q))
urlParams[d(e[1])] = d(e[2]);
})();
// helper function for getting the "top" coordinate of an object
function tpGetTop(obj) {
result = 0;
while (obj) {
result += obj.offsetTop;
obj = obj.offsetParent;
}
return result;
}
function flashHeartbeat(responseCode, message) {
window.console && console.log("flashHeartbeat called: ", arguments);
var result = RJS.Event.trigger('flashHeartbeat', { responseCode: responseCode, message: message });
if (!result) return;
}
var overlayLastLoaded = null;
// function called when video has ended / restarted
function flashShowOverlay(assetId) {
window.console && console.log("flashShowOverlay called: ", arguments);
flashRaiseLight();
var result = RJS.Event.trigger('flashShowOverlay', assetId);
if (!result) return;
var overlay = jQuery(".overlay");
var video = jQuery("#videoOverlay");
var p = RJS.Player.player;
if (!p && RJS.Player && "init" in RJS.Player) {
RJS.Player.init();
p = RJS.Player.player;
}
if (p && !overlay.hasClass('global-overlay')) {
var newWidth = 615;
var newHeight = 345;
//p.flashResize(newWidth, newHeight);
p.style.width = newWidth + "px";
p.style.height = newHeight + "px";
if (overlay.hasClass('crackle-overlay')) {
RJS.Player.wrapper.style.margin = "0 auto";
} else {
RJS.Player.wrapper.style.marginLeft = "0";
}
}
video.fadeIn();
overlay.show();
jQuery("h2.return").hide();
if (typeof assetId === 'undefined') {// If no assetID is given, make an attempt to find the assetID manually.
var a = document.getElementById('assetID');
if (a) { assetId = a.value; }
}
if (typeof assetId !== 'undefined' && (overlayLastLoaded === null || overlayLastLoaded < new Date(new Date().setSeconds(-5)))) {
overlayLastLoaded = new Date();
overlay.load(URLUtil.resolveUrl("~/handlers/morevideos.aspx?aid=" + assetId));
} else {
window.console && console.log("Overlay handler could not be loaded. Either the Asset ID is null, or this function call has been rate limited. assetId: ", assetId);
}
RJS.Player.ad && RJS.Player.ad.fadeIn();
}
jQuery(".dimLight a, a.dimLight").live("click mouseover", function(e) {
e.stopPropagation();
e.preventDefault();
e.stopImmediatePropagation();
return false;
})
// Dim the Lights control
function flashDimLight() {
var mainHeight = jQuery("#main").height();
var footerHeight = jQuery("#footer-wrap").height();
jQuery("#lightDimmer").height(mainHeight + footerHeight);
jQuery("#main:not('.register-page'), #footer-wrap").addClass('dimMain');
var dimElements = jQuery(".imgWrap img, #selector select, .titlebar h4, .titlebar p, .titlebar a, .rated, #rate-it span,#lightDimmerTop, #lightDimmer, #lightDimmerFoot, .titlebar,.channelSkin,.tandemAd, .curated-template");
if (jQuery("body").hasClass("rental-page")) {
dimElements.add("#detail-summary-outer, #rentals-head-wrap, #rental-head,#lightDimmerRental");
}
dimElements.addClass('dimLight');
}
function flashRaiseLight() {
jQuery("#main, #footer-wrap").removeClass('dimMain');
var dimElements = jQuery(".imgWrap img, #selector select, .titlebar h4, .titlebar p, .titlebar a, .rated, #rate-it span,#lightDimmerTop, #lightDimmer, #lightDimmerFoot, .titlebar,.channelSkin,.tandemAd, .curated-template");
if (jQuery("body").hasClass("rental-page")) {
dimElements.add("#detail-summary-outer, #rentals-head-wrap, #rental-head,#lightDimmerRental");
}
dimElements.removeClass('dimLight');
}
function flashHideOverlay() {
var newHeight = RJS.Player.getNumberFromAttribute('data-original-height', 457),
newWidth = RJS.Player.getNumberFromAttribute('data-original-width', 768);
//RJS.Player.player.flashResize(newWidth, newHeight);
RJS.Player.player.style.width = newWidth + "px";
RJS.Player.player.style.height = newHeight + "px";
RJS.Player.wrapper.style.marginLeft = "auto";
RJS.Player.ad.fadeOut();
jQuery("#videoOverlay").fadeOut("slow");
jQuery(".overlay").hide();
}
// helper function for getting the "left" coordinate of an object
function tpGetLeft(obj) {
result = 0;
while (obj) {
result += obj.offsetLeft;
obj = obj.offsetParent;
}
return result;
}
tpThisMovie = function(movieName) {
var oDoc
if (window.frame) {
oDoc = frame.contentWindow.document || frame.contentDocument.document;
}
else {
oDoc = document
}
return oDoc.getElementById(movieName);
}
function tpDebug(str) {
if (document.getElementById("debugDiv")) {
document.getElementById("debugDiv").innerHTML += str + "<br>";
}
}
// open a new pop-up window
function tpOpenNewWindow(URLtoOpen, windowName, windowFeatures) {
var newWindow = window.open(URLtoOpen, windowName, windowFeatures);
}
// handle tracking URLs
var tpTrackingImage = new Image();
function tpCallTrackingUrl(url) {
url = unescape(url);
tpTrackingImage.src = url;
for (i = 0; ((!tpTrackingImage.complete) && (i < 100000)); i++) {
}
}
///// INIT tpController //////////
function tpGetUseJS() { return "true" }
function tpGetInstanceID() { return tpInstanceID; }
function tpGetCommManagerID() { return tpCommID; }
tpLogLevel = "warn";
function tpSetLogLevel(level) { tpLogLevel = level };
function tpGetLogLevel() { return tpLogLevel }
function tpGetProperties() {
//each pdk controller will call this to get the default properties
var props = new Object();
props.commManagerId = tpGetCommManagerID();
props.instanceId = tpGetInstanceID();
props.useJS = tpGetUseJS();
props.registeredComponents = tpGetRegisteredIDs();
props.logLevel = tpGetLogLevel();
return props;
}
var registeredIDs = new Array();
function tpRegisterID(swfName) {
for (var i = 0; i < registeredIDs.length; i++) {
if (registeredIDs[i] == swfName) return;
}
registeredIDs.push(swfName);
}
function tpGetRegisteredIDs() {
return registeredIDs;
}
// handle references to the communication manager
var tpController;
var tpCommID;
var tpBridgeID;
var tpExternalController;
//the kicks off the creation of the tpController, must be called before any pdk components are set on the page
function tpSetCommManagerID(commID, embed, commManagerUrl) {
// create a unique token for each set of player controls
tpInstanceID = (new Date()).getTime() + "|" + Math.round(Math.random() * 100000000000000000);
if (commID && embed) {
//get rid of any existing commManager
var divEl = window.document.getElementById("commManagerDiv");
if (divEl) {
divEl.parentNode.removeChild(divEl);
divEl = null;
}
//create a commManager as the first element in the body
divEl = window.document.createElement('div');
divEl.id = "commManagerDiv";
divEl.style.position = "absolute";
var bodyTag = window.document.getElementsByTagName('body')[0];
bodyTag.insertBefore(divEl, bodyTag.firstChild);
var url = commManagerUrl ? commManagerUrl : "swf/commManager.swf"
var so = new SWFObject(url, commID, "1", "1", "9.0.0.0");
so.addParam("allowScriptAccess", "always");
so.addParam("wmode", "transparent");
so.write("commManagerDiv");
}
tpController = new tpControllerClass();
tpCommID = commID;
tpBridgeID = commID ? commID : "unknown";
//external controller
//tpCleanupExternal();
}
//function flashMediaStart(width, height) {
//    alert("ad is playing");
//    width = 614;
//    height = 399;
//    jQuery("#player-wrap").addClass("test");
//}
//function flashMediaEnd() {
//    alert("ad is done");
//    jQuery("#player-wrap").removeClass("test");
//}
///// TPCONTROLLER CLASS /////////////
// implementation of the controller proxy in javascript
function tpControllerClass() {
//vars loaded at bottom
/////// Send Messages to the rest of the app //////////////
///////////////////////////////////////////////////////////
//all communication to the communication manager happens here
this.sendMessage = function(destination, message, skipBus) {
//tpDebug("putting message on queue: " + message.name + " skipBus?" + skipBus + " canMessage?" + this.canMessage + " isLoading?" + this.isLoading);
var sendObj = new Object();
sendObj.message = message;
sendObj.destination = destination;
if (this.isLoading && !skipBus) {
//these are low priority messages that should be sent only after OnPlayerLoaded is fired
this.messageQueue.push(sendObj);
}
else if (!this.canMessage) {
//these are high priority messages (like addEventListener or registerFunction) that usually need to be sent before OnPlayerLoaded is fired
//but we still have to wait until after the communication manager has loaded or they'll just disappear
this.priorityQueue.push(sendObj);
}
else {
this.doSendMessage(sendObj);
}
}
this.doSendMessage = function(sendObj)//private function
{
if (this.isShutDown) return;
var obj = tpThisMovie(sendObj.destination);
//tpDebug("sending: " + sendObj.message.name + " dest:" + sendObj.destination);
// Flash ExternalInterface will convert any "" or " " string to null.  However,
// in the PDK, null and "" mean different things.  So, if there are blank strings,
// convert to a signal value, and then unconvert on the way out.
/*for (var i=0; i<sendObj.parameters.length; i++)
{
var param = sendObj.parameters[i];
if (typeof param == "string" && (param.length == 0 || param == " "))
{
sendObj.parameters[i] = this.blankString;
}
}*/
//tpDebug("do send message: " + sendObj.message.name);
obj.executeMessage(sendObj.message);
}
this.checkMessageQueue = function()//private function
{
var len = this.messageQueue.length
while (this.messageQueue.length > 0) {
this.doSendMessage(this.messageQueue.shift());
}
}
this.checkPriorityQueue = function() {
while (this.priorityQueue.length > 0) {
var sendObj = this.priorityQueue.shift();
if (sendObj.destination == "unknown") sendObj.destination = tpBridgeID;
this.doSendMessage(sendObj);
}
}
this.wrapMessage = function(messageName, payload) {
var comm = { globalDataType: this.getDataTypeName("CommInfo"), id: "javascript" }
var message = { globalDataType: this.getDataTypeName("MessageInfo"), name: messageName, payload: payload, comm: comm };
return message;
}
this.getDataTypeName = function(shortType) {
switch (shortType) {
case "ScopeInfo": return "com.theplatform.pdk.communication::ScopeInfo";
case "MessageInfo": return "com.theplatform.pdk.communication::MessageInfo";
case "DispatchInfo": return "com.theplatform.pdk.communication::DispatchInfo";
case "HandlerInfo": return "com.theplatform.pdk.communication::HandlerInfo";
case "CommInfo": return "com.theplatform.pdk.communication::CommInfo";
case "CallInfo": return "com.theplatform.pdk.communication::CallInfo";
case "FunctionInfo": return "com.theplatform.pdk.communication::FunctionInfo";
case "PdkEvent": return "com.theplatform.pdk.events::PdkEvent";
case "Clip": return "com.theplatform.pdk.data::Clip";
case "BaseClip": return "com.theplatform.pdk.data::BaseClip";
case "Banner": return "com.theplatform.pdk.data::Banner";
case "Overlay": return "com.theplatform.pdk.data::Overlay";
case "HyperLink": return "com.theplatform.pdk.data::HyperLink";
case "TrackingUrl": return "com.theplatform.pdk.data::TrackingUrl";
case "CustomData": return "com.theplatform.pdk.data::CustomData";
case "Subtitles": return "com.theplatform.pdk.data::Subtitles";
case "AdPattern": return "com.theplatform.pdk.data::AdPattern";
case "Range": return "com.theplatform.pdk.data::Range";
case "Sort": return "com.theplatform.pdk.data::Sort";
}
}
this.createScope = function(scope) {
if (scope == undefined) return this.defaultScope;
else {
scope.push("javascript");
return { globalDataType: this.getDataTypeName("ScopeInfo"), controlId: "javascript", isGlobal: "true", isAny: "false", isEmpty: "false", scopeIds: scope };
}
}
//////// handle communication to the rest of the app ///////
////////////////////////////////////////////////////////////
//register a function
this.registerFunction = function(funcName, callback, scopes) {
var scopeObj = this.createScope(scopes);
var informComm = false;
if (this.functions[funcName] == undefined) {
this.functions[funcName] = new Object();
informComm = true;
}
for (var i = 0; i < scopeObj.scopeIds.length; i++) {
var s = scopeObj.scopeIds[i];
if (s == "*") return; //can't register a scope of any
this.functions[funcName][s] = callback;
}
if (informComm) {
//send the registered function to the commManager
var func = { globalDataType: this.getDataTypeName("FunctionInfo"), name: funcName, scope: scopeObj };
var message = this.wrapMessage("registerFunction", func);
this.sendMessage(tpBridgeID, message, true);
}
}
this.unregisterFunction = function(funcName, scope) {
var scopeObj = this.createScope(scopes);
if (this.functions[funcName] != undefined) {
var funcs = this.functions[funcName];
for (var i = 0; i < scopeObj.scopeIds.length; i++) {
var s = scopeObj.scopeIds[i];
if (s == "*") {
delete funcs; //delete them all
break;
}
if (funcs[s] != undefined) delete funcs[s]; //delete each scope
}
var funcsLeft = false;
if (funcs != undefined)//prune the object
{
for (var sc in funcs) {
funcsLeft = true;
break;
}
if (!funcsLeft) delete this.functions[funcName];
}
}
if (!funcsLeft) {
var func = { globalDataType: this.getDataTypeName("FunctionInfo"), name: funcName, scope: scopeObj };
var message = this.wrapMessage("unregisterFunction", func);
this.sendMessage(tpBridgeID, message, true);
}
}
this.addEventListener = function(eventName, callback, scope) {
var scopeObj = this.createScope(scope);
var handler = { globalDataType: this.getDataTypeName("HandlerInfo"), name: eventName, handler: callback, scope: scopeObj }
var informComm = false;
if (this.events[eventName] == undefined) {
this.events[eventName] = new Array();
informComm = true;
}
var evts = this.events[eventName];
var repeat = false;
for (var i = 0; i < evts.length; i++)//repeats?
{
if (evts[i].handler == callback) {
evts[i] = handler; //replace the scopes
repeat = true;
break;
}
}
if (!repeat) evts.push(handler);
if (informComm) {
var message = this.wrapMessage("addEventListener", handler);
this.sendMessage(tpBridgeID, message, true);
}
}
this.removeEventListener = function(eventName, callback, scope) {
if (this.events[eventName] != undefined) {
var scopeObj = this.createScope(scope);
var handler = { globalDataType: this.getDataTypeName("HandlerInfo"), name: eventName, handler: callback, scope: scopeObj }
var eventArray = this.events[eventName];
for (var i = 0; i < eventArray.length; i++) {
var h = eventArray[i];
if (h.handler == handler.handler) {
eventArray = eventArray.splice(i, 1);
break;
}
}
if (eventArray.length == 0) {
//no callbacks left, zap the variable
delete this.events[eventName];
var message = this.wrapMessage("removeEventListener", handler);
this.sendMessage(tpBridgeID, message, true)
}
}
}
this.dispatchEvent = function(eventName, value, scope) {
var scopeObj = this.createScope(scope);
var evt = { globalDataType: this.getDataTypeName("PdkEvent"), type: eventName, data: value };
var dispatch = { globalDataType: this.getDataTypeName("DispatchInfo"), evt: evt, scope: scopeObj };
//check local events
this.doDispatchEvent(dispatch);
var message = this.wrapMessage("dispatchEvent", dispatch);
this.sendMessage(tpBridgeID, message, true);
}
this.callFunction = function(funcName, args, scope) {
var scopeObj = this.createScope(scope);
var call = { globalDataType: this.getDataTypeName("CallInfo"), name: funcName, args: args, scope: scopeObj };
this.doCallFunction(call);
var message = this.wrapMessage("callFunction", call);
this.sendMessage(tpBridgeID, message, true);
}
this.doDispatchEvent = function(dispatch) {
//tpDebug("do dispatching event: " + dispatch.evt.type);
if (this.events[dispatch.evt.type] != undefined) {
var handlers = this.events[dispatch.evt.type]
for (var i = 0; i < handlers.length; i++) {
var handler = handlers[i];
if (dispatch.scope.isAny) {
eval(handler.handler)(dispatch.evt);
continue;
}
for (var j = 0; j < handler.scope.scopeIds.length; j++) {
var s = handler.scope.scopeIds[j];
var fired = false;
if (s == "*") {
eval(handler.handler)(dispatch.evt);
break;
}
for (var k = 0; k < dispatch.scope.scopeIds.length; k++) {
if (s == dispatch.scope.scopeIds[k]) {
fired = true;
eval(handler.handler)(dispatch.evt);
break;
}
}
if (fired) break; //go to next handler
}
}
}
}
this.doCallFunction = function(call) {
if (this.functions[call.name] != undefined) {
//check local functions
var funcsToCall = new Object();
for (var i = 0; i < call.scope.scopeIds.length; i++) {
var s = call.scope.scopeIds[i];
if (this.functions[call.name][s] != undefined) {
funcsToCall[this.functions[call.name][s]] = "f"; //we need lookup
}
}
for (var f in funcsToCall) {
eval(f)(call.args);
}
}
}
//////// RECEIVE CALLS FROM AS //////////////
////////////////////////////////////////////
//all communication from the communication manager happens here
this.receiveMessage = function(destination, message) {
if (destination == "javascript") {
//tpDebug("receiving message: " + message.name)
var messStr = message.name;
switch (messStr) {
case "commReady":
tpBridgeID = tpCommID;
this.canMessage = true;
this.checkPriorityQueue();
break;
case "bridgeReady":
tpBridgeID = message.comm.id;
this.canMessage = true;
this.checkPriorityQueue();
break;
case "dispatchEvent":
var dispatch = message.payload;
this.receiveEvent(dispatch);
break;
case "callFunction":
var call = message.payload;
this.doCallFunction(call);
break;
default:
break;
}
}
else {
//transfer the message to its final destination
this.sendMessage(destination, message, true);
}
}
this.receiveEvent = function(dispatch) {
//tpDebug("RECIEVED:" + dispatch.evt.type)
if (dispatch.evt.type == "OnPlayerLoaded") {
this.isLoading = false;
this.checkMessageQueue();
}
this.doDispatchEvent(dispatch);
}
//create a list of direct calls
// PLAYER
this.setRelease = function(release, replaceDefault, scope) {
var args = [release, replaceDefault];
this.callFunction("setRelease", args, scope);
}
this.loadRelease = function(release, replaceDefault, scope) {
var args = [release, replaceDefault];
this.callFunction("loadRelease", args, scope);
}
this.loadReleaseURL = function(releaseURL, replaceDefault, scope) {
var args = [releaseURL, replaceDefault];
this.callFunction("loadReleaseURL", args, scope);
}
this.setReleaseURL = function(url, replaceDefault, scope) {
var args = [url, replaceDefault];
this.callFunction("setReleaseURL", args, scope);
}
this.setCurrentReleaseList = function(id, scope) {
var args = [id];
this.callFunction("setCurrentReleaseList", args, scope);
}
this.seekToPosition = function(position, scope) {
var args = [position];
this.callFunction("seekToPosition", args, scope);
}
this.seekToPercentage = function(percent, scope) {
var args = [percent];
this.callFunction("seekToPercentage", args, scope);
}
this.nextClip = function(scope) {
var args = ["javascript"];
this.callFunction("nextClip", args, scope);
}
this.previousClip = function(scope) {
var args = [];
this.callFunction("previousClip", args, scope);
}
this.mute = function(muted, scope) {
var args = [muted];
this.callFunction("mute", args, scope);
}
this.pause = function(paused, scope) {
var args = [paused];
this.callFunction("pause", args, scope);
}
this.showFullScreen = function(isFullScreen, scope) {
var args = [isFullScreen];
this.callFunction("showFullScreen", args, scope);
}
this.showEmailForm = function(visible, scope) {
var args = [visible];
this.callFunction("showEmailForm", args, scope);
}
this.showLinkForm = function(visible, scope) {
var args = [visible];
this.callFunction("showLinkForm", args, scope);
}
this.trace = function(str, className, level) {
var args = [str, className, level];
this.callFunction("trace", args, null);
}
this.useDefaultPlayOverlay = function(useDefault, scope) {
var args = [useDefault];
this.callFunction("useDefaultPlayOverlay", args, scope);
}
this.getUseDefaultPlayOverlay = function(scope) {
var args = [];
this.callFunction("getUseDefaultPlayOverlay", args, scope);
}
this.useDefaultLinkForm = function(useDefault, scope) {
var args = [useDefault];
this.callFunction("useDefaultLinkForm", args, scope);
}
this.useDefaultEmailForm = function(useDefault, scope) {
var args = [useDefault];
this.callFunction("useDefaultEmailForm", args, scope);
}
this.getSubtitleLanguage = function(requestor, scope) {
var args = [requestor];
this.callFunction("getSubtitleLanguage", args, scope);
}
this.clickPlayButton = function(scope) {
var args = [];
this.callFunction("clickPlayButton", args, scope);
}
this.disablePlayerControls = function(disable, exceptions, scope) {
var args = [disable, exceptions];
this.callFunction("disablePlayerControls", args, scope);
}
this.setSubtitleLanguage = function(language, scope) {
var args = [language];
this.callFunction("setSubtitleLanguage", args, scope);
}
this.getPlayerVariables = function(names, scope) {
var args = [names];
this.callFunction("getPlayerVariables", args, scope);
}
this.setVolume = function(volume, scope) {
var args = [volume];
this.callFunction("setVolume", args, scope);
}
// RELEASE MODEL
this.refreshReleaseModel = function(category, search, sort, range, params, secondaryParams, scope) {
if (sort) sort.globalDataType = this.getDataTypeName("Sort");
if (range) range.globalDataType = this.getDataTypeName("Range");
var args = [category, search, sort, range, params, secondaryParams];
this.callFunction("refreshReleaseModel", args, scope);
}
// CATEGORY MODEL
this.refreshCategoryModel = function(params, scope) {
var args = [params];
this.callFunction("refreshCategoryModel", args, scope);
}
// NAVIGATION
this.nextRange = function(scope) {
var args = [];
this.callFunction("nextRange", args, scope);
}
this.previousRange = function(scope) {
var args = [];
this.callFunction("previousRange", args, scope);
}
// CLIP INFO
this.setClipInfo = function(clip, isDefault, scope) {
clip = this.modClip(clip);
var args = [clip, isDefault];
this.callFunction("setClipInfo", args, scope);
}
// CATEGORY LIST
this.clearCategorySelection = function(scope) {
var args = [];
this.callFunction("clearCategorySelection", args, scope);
}
// RELEASE LIST
this.suspendPlayAll = function(suspend, scope) {
var args = [suspend];
this.callFunction("suspendPlayAll", args, scope);
}
this.playNext = function(wrapAround, naturalEnd, scope) {
var args = [wrapAround, naturalEnd];
this.callFunction("playNext", args, scope);
}
this.playPrevious = function(wrapAround, scope) {
var args = [wrapAround];
this.callFunction("playPrevious", args, scope);
}
// GENERAL
this.modClip = function(clip) {
if (clip) {
//set the class names correctly for casting in as3.
clip.globalDataType = this.getDataTypeName("Clip");
var baseClip = clip.baseClip;
if (!baseClip) baseClip = new Object();
if (clip.banners) baseClip.banners = clip.banners;
if (clip.overlays) baseClip.overlays = clip.overlays;
clip.baseClip = this.modBaseClip(baseClip);
if (clip.chapter) clip.chapter.globalDataType = this.getDataTypeName("Chapter");
}
return clip;
}
this.modBaseClip = function(baseClip) {
if (!baseClip) baseClip = new Object();
baseClip.globalDataType = this.getDataTypeName("BaseClip");
if (baseClip.moreInfo) {
baseClip.moreInfo.globalDataType = this.getDataTypeName("HyperLink");
if (baseClip.moreInfo.clickTrackingUrls) baseClip.moreInfo.clickTrackingUrls = this.modTracking(baseClip.moreInfo.clickTrackingUrls);
}
if (baseClip.banners) {
for (var i = 0; i < baseClip.banners.length; i++) {
baseClip.banners[i].globalDataType = this.getDataTypeName("Banner");
if (baseClip.banners[i].clickTrackingUrls) baseClip.banners[i].clickTrackingUrls = this.modTracking(baseClip.banners[i].clickTrackingUrls)
}
}
if (baseClip.overlays) {
for (var i = 0; i < baseClip.overlays.length; i++) {
baseClip.overlays[i].globalDataType = this.getDataTypeName("Overlay");
if (baseClip.overlays[i].clickTrackingUrls) baseClip.overlays[i].clickTrackingUrls = this.modTracking(baseClip.overlays[i].clickTrackingUrls)
}
}
if (baseClip.availableSubtitles) {
for (var i = 0; i < baseClip.availableSubtitles; i++) {
baseClip.availableSubtitles[i].globalDataType = this.getDataTypeName("Subtitles");
}
}
if (baseClip.adPattern) baseClip.adPattern.globalDataType = this.getDataTypeName("AdPattern");
if (baseClip.trackingURLs) baseClip.trackingURLs = this.modTracking(baseClip.trackingURLs);
if (baseClip.contentCustomData) baseClip.contentCustomData.globalDataType = this.getDataTypeName("CustomData");
if (baseClip.ownerCustomData) baseClip.ownerCustomData.globalDataType = this.getDataTypeName("CustomData");
if (baseClip.outletCustomData) baseClip.outletCustomData.globalDataType = this.getDataTypeName("CustomData");
return baseClip;
}
this.modTracking = function(trackingUrls) {
for (var i = 0; i < trackingUrls.length; i++) {
trackingUrls.globalDataType = this.getDataTypeName("TrackingUrl")
}
return trackingUrls
}
this.shutDown = function() {
var args = [];
this.callFunction("shutDown", args, ["*"]);
this.isShutDown = true; //prevent any more messages
}
//vars initialized
this.events = new Object();
this.functions = new Object();
this.isLoading = true;
this.canMessage = false;
this.messageQueue = new Array();
this.priorityQueue = new Array();
this.sendQueue = new Array(); //yet another queue for timing externalInterface calls
this.isSending = false;
this.sendInterval;
this.shutdownIDs; //array to keep all the controller ids for shutdown
this.isShutDown = false;
this.blankString = "__blank_string__";
this.defaultScope = { globalDataType: this.getDataTypeName("ScopeInfo"), controlId: "javascript", isGlobal: true, isAny: false, isEmpty: false, scopeIds: ["javascript", "default"] };
}
function tpReceiveMessage(destination, message) {
//tpDebug("---message received---" + message.name + " dest:" + destination)
tpController.receiveMessage(destination, message);
}
//functions for controlling external players
var tpHolderName = "pdkHolder";
var tpExternalJS;
function tpSetPlayerIDForExternal(playerName) { }; //no longer needed
function tpSetHolderIDForExternal(holderName)//needed
{
tpHolderName = holderName;
}
function tpLoadExternalMediaJS() {
tpExternalJS = tpLoadExternalMediaJS.arguments;
for (var i = 0; i < tpExternalJS.length; i++) {
tpLoadScript(tpExternalJS[i]);
}
}
function tpCleanupExternal() {
if (tpExternalJS)//if there's no external js, then nothing was loaded in
{
var scripts = window.document.getElementsByTagName('head')[0].getElementsByTagName('script');
for (var i = 0; i < scripts.length; i++) {
for (var j = 0; j < tpExternalJS.length; j++) {
if (scripts[i].src == tpExternalJS[j]) {
window.document.getElementsByTagName('head')[0].removeChild(scripts[i]);
break;
}
}
}
tpExternalJS.length = 0;
}
if (tpExternalController) {
tpExternalController.cleanup();
}
}
/////////////////////////////////////////////////////////////////////
tpScriptLoader = new ScriptLoader();
// called from flash via ExternalInterface
function tpLoadJScript(scriptFile, callback, id, atts) {
tpScriptLoader.addScript(scriptFile, callback, id, atts);
}
// need to wrap method to fix scoping issue on callback
function callbackDispatcher(loadObj) { tpScriptLoader.callbackDispatcher(loadObj) }
function invokeCallbacks(loadObj) { tpScriptLoader.invokeCallbacks() }
/////////////////////////////////////////////////////////////////////
//					L O A D   O B J E C T
/////////////////////////////////////////////////////////////////////
function LoadObj(scriptFile, callback, id, atts) {
this.script = scriptFile;
this.callback = callback;
this.id = id;
this.atts = atts;
}
/////////////////////////////////////////////////////////////////////
//					S C R I P T   L O A D E R
/////////////////////////////////////////////////////////////////////
// constructor
function ScriptLoader() {
// queued up for loading scripts
this.scriptQueue = new Array();
// queued up for invoking callbacks
this.callbackQueue = new Array();
}
/////////////////////////////////////////////////////////////////////
ScriptLoader.prototype.addScript = function(scriptFile, callback, id, atts) {
var loadObj = new LoadObj(scriptFile, callback, id, atts);
this.scriptQueue.push(loadObj);
// if the queue was empty, we need to kick
// off the queue processing again.
if (this.scriptQueue.length == 1)
this.checkScriptQueue();
}
/////////////////////////////////////////////////////////////////////
ScriptLoader.prototype.checkScriptQueue = function() {
if (this.scriptQueue.length) {
var loadObj = this.scriptQueue.shift();
this.loadScript(loadObj);
}
else {
// as a timing precaution, we wait until the queue
// empties out before we invoke callbacks
interval_id = setInterval("invokeCallbacks()", 100) // more timing precautions :-/
//this.invokeCallbacks();
}
}
/////////////////////////////////////////////////////////////////////
ScriptLoader.prototype.callbackDispatcher = function(loadObj) {
for (var i in this.callbackQueue) {
if (this.callbackQueue[i] == loadObj) {
this.checkScriptQueue();
return;
}
}
this.callbackQueue.push(loadObj);
this.checkScriptQueue();
}
/////////////////////////////////////////////////////////////////////
ScriptLoader.prototype.invokeCallbacks = function() {
clearInterval(interval_id);
while (this.callbackQueue.length) {
var loadObj = this.callbackQueue.shift();
eval(loadObj.callback)(loadObj.script);
}
}
/////////////////////////////////////////////////////////////////////
ScriptLoader.prototype.loadScript = function(loadObj) {
var scriptFilename = loadObj.script;
var callbackFunction = loadObj.callback;
var id = loadObj.id;
var atts = loadObj.atts;
// Create script element and set it to load the requested script
var scriptEl = window.document.createElement('script');
scriptEl.charset = "utf-8";
if (id) scriptEl.id = id;
scriptEl.type = "text/javascript";
//scriptEl.defer = true;
if (atts) {
for (var i = 0; i < atts.length; i++)
scriptEl.setAttribute(atts[i].att, atts[i].value);
}
scriptEl.src = scriptFilename;
if (callbackFunction) {
// Function to be called when script has finished loading
var _onFinished = function(_loadObj, _callback) {
// Invoke the callback function
_callback(_loadObj)
// Clean up event handlers
this.onreadystatechange = null;
this.onload = null;
this.onerror = null;
};
// Set callback for IE
// In defiance of MSDN documentation IE's script object has no onload handler
scriptEl.onreadystatechange = function() {
_onFinished(loadObj, callbackDispatcher);
};
// Set callback for W3C-compatible browsers
scriptEl.onload = function() {
_onFinished(loadObj, callbackDispatcher);
};
// Set another callback for W3C-compatible browsers
// since onreadystatechange for IE also fires in case of an error
scriptEl.onerror = function() {
_onFinished(loadObj, callbackDispatcher);
};
}
// Add script element to the document
window.document.getElementsByTagName('head')[0].appendChild(scriptEl);
}
/////////////////////////////////////////////////////////////////////
// ORIGINAL LOADSCRIPT - USED BY MOVENETWORKS
/////////////////////////////////////////////////////////////////////
function tpLoadScript(scriptFilename, callbackFunction, id, atts) {
// Create script element and set it to load the requested script
var scriptEl = window.document.createElement('script');
scriptEl.charset = "utf-8";
if (id) scriptEl.id = id;
scriptEl.type = "text/javascript";
//scriptEl.defer = true;
if (atts) {
for (var i = 0; i < atts.length; i++) {
scriptEl.setAttribute(atts[i].att, atts[i].value);
}
}
scriptEl.src = scriptFilename;
if (callbackFunction) {
// Function to be called when script has finished loading
var _onFinished = function(_callbackFunction, _scriptFilename) {
// Invoke the callback function
_callbackFunction(_scriptFilename);
// Clean up event handlers
this.onreadystatechange = null;
this.onload = null;
this.onerror = null;
};
// Set callback for IE
// In defiance of MSDN documentation IE's script object has no onload handler
scriptEl.onreadystatechange = function() {
_onFinished(callbackFunction, scriptFilename);
};
// Set callback for W3C-compatible browsers
scriptEl.onload = function() {
_onFinished(callbackFunction, scriptFilename);
};
// Set another callback for W3C-compatible browsers
// since onreadystatechange for IE also fires in case of an error
scriptEl.onerror = function() {
_onFinished(callbackFunction, scriptFilename);
};
}
// Add script element to the document
window.document.getElementsByTagName('head')[0].appendChild(scriptEl);
}
/////////////////////////////////////////////////////////////////////
//constructor for tpExternalControl
function tpExternalControllerClass() {
this.playerTypes = new Object(); //keep a lookup of classes
this.extPlayers = new Object(); //keep the instances here
this.registerExternalPlayer = function(type, playerClass) {
this.playerTypes[type] = playerClass; //keep the class as a string
}
this.routeMessage = function(swfId, controllerId, streamType, funcName, args) {
var curController = this.extPlayers[controllerId]; //see if we have the existing controller lookup
if (!curController) curController = this.extPlayers[controllerId] = {}; //make a lookup for the controller
var curPlayer = curController[streamType]; //now see if we have the actual player object instantiated
if (!curPlayer) {
var playerClass = this.playerTypes[streamType];
if (!playerClass) return; //we don't have the correct stream type on hand
curPlayer = eval("new " + playerClass + "('" + swfId + "', '" + controllerId + "');"); //create a new instance of the class
if (!curPlayer) return; //abort here, too
curController[streamType] = curPlayer;
}
curPlayer[funcName](args);
}
this.returnMessage = function(swfId, controllerId, funcName, args) {
var obj = tpThisMovie(swfId);
obj.receiveJSMessage(controllerId, funcName, args);
}
this.cleanup = function() {
for (var controllerId in this.extPlayers) {
var players = this.extPlayers[controllerId];
for (var player in players) {
players[player].cleanup();
delete players[player];
}
delete this.extPlayers[controllerId];
}
}
}
function tpExternalMessage(swfId, controllerId, streamType, funcName, args) {
tpExternalController.routeMessage(swfId, controllerId, streamType, funcName, args);
}
//build this without needing the commManager
tpExternalController = new tpExternalControllerClass();
function tpShowAlert(alertCode) {
switch (alertCode) {
case "FULLSCREEN_DISABLED":
//if (deconcept.SWFObjectUtil.getPlayerVersion().major < 9)
alert("Full screen is only available with Flash 9 or later")
break;
}
}


