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';
        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) {
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;
}
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(); }
}
};
RJS.Event = (function() {
var events = {};
return {
bind: function(eventName, handler) {
if (typeof events[eventName] === "undefined") {
events[eventName] = [];
}
events[eventName].push(handler);
},
trigger: function(eventName, data) {
if (typeof events[eventName] !== "undefined") {
for (var i = 0; i < events[eventName].length; i++) {
events[eventName][i](data);
}
}
}
};
})();
jQuery(function($) {
$("a:external").live("click", function(ev){
ev.preventDefault();
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) {
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 = "";
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"), "");
}
RJS.Mouse = { x: 0, y: 0 };
jQuery(document.body).mousemove(function(ev) {
RJS.Mouse.x = ev.pageX;
RJS.Mouse.y = ev.pageY;
});
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];
}
jQuery.expr[':'].external = function(a) {
return a.href && !a.href.match(/^mailto\:/) && a.hostname && (a.hostname != location.hostname);
};
(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);
}
function getHeightDiff(outer, inner, excludeMargin) {
var paddingHeight = parseInt(outer.css("padding-top").replace("px", ""), 10)
+ parseInt(outer.css("padding-bottom").replace("px", ""), 10);
var marginHeight = parseInt(inner.css("margin-top").replace("px", ""), 10)
+ parseInt(inner.css("margin-bottom").replace("px", ""), 10);
if (excludeMargin === true) paddingHeight;
return paddingHeight + marginHeight;
};
var continueResizing = false;
function resizeLightbox() {
try {
var contentSelector = "form";
var padding = 10;
var iframe = $("#cboxIframe");
if (iframe.length === 0 || !iframe.is(":visible") || iframe.contents().length === 0) {
if (continueResizing === true) {
setTimeout(resizeLightbox, resizeLightbox.updateInterval);
}
return;
}
var form = iframe.contents().find(contentSelector);
if (form.length === 0) {
if (continueResizing === true) {
setTimeout(resizeLightbox, resizeLightbox.updateInterval);
}
return;
}
var colorbox = $("#colorbox"),
wrapper = $("#cboxWrapper"),
content = $("#cboxContent"),
contentLeft = $("#cboxMiddleLeft"),
contentRight = $("#cboxMiddleRight"),
loadedContent = $("#cboxLoadedContent");
var wrapperHeightDiff = getHeightDiff(colorbox, wrapper);
var outerHeightDiff = getHeightDiff(wrapper, content);
var innerHeightDiff = getHeightDiff(content, loadedContent);
var iframeContentHeightDiff = getHeightDiff(loadedContent, iframe);
var sideTopBottomSize = 0;
if (!colorbox.hasClass("fifa")) {
// The +9 below is for the height of the drop-shadow background image corner, which can't be derived using JavaScript and needs to be hard-coded :-/
sideTopBottomSize = parseInt(contentLeft.css("top").replace("px", ""), 10) + 9;
}
var actualHeight = form.outerHeight(true);
actualHeight += padding;
content.closest("body").height(actualHeight);
iframe.height(actualHeight);
loadedContent.height(actualHeight + iframeContentHeightDiff);
content.height(actualHeight + iframeContentHeightDiff + innerHeightDiff);
contentLeft.height((actualHeight + iframeContentHeightDiff + innerHeightDiff) - sideTopBottomSize);
contentRight.height((actualHeight + iframeContentHeightDiff + innerHeightDiff) - sideTopBottomSize);
wrapper.height(actualHeight + iframeContentHeightDiff + innerHeightDiff + outerHeightDiff);
colorbox.height(actualHeight + iframeContentHeightDiff + innerHeightDiff + outerHeightDiff + wrapperHeightDiff);
colorbox.css("visibility", "visible");
} catch (e) { }
if (continueResizing === true) {
setTimeout(resizeLightbox, resizeLightbox.updateInterval);
}
}
function resizeHtml() {
try {
var colorbox = $("#colorbox"),
wrapper = $("#cboxWrapper"),
content = $("#cboxContent"),
contentLeft = $("#cboxMiddleLeft"),
contentRight = $("#cboxMiddleRight"),
loadedContent = $("#cboxLoadedContent");
var wrapperHeightDiff = getHeightDiff(colorbox, wrapper);
var outerHeightDiff = getHeightDiff(wrapper, content);
var innerHeightDiff = getHeightDiff(content, loadedContent);
var sideTopBottomSize = 0;
if (!colorbox.hasClass("fifa")) {
// The +9 below is for the height of the drop-shadow background image corner, which can't be derived using JavaScript and needs to be hard-coded :-/
sideTopBottomSize = parseInt(contentLeft.css("top").replace("px", ""), 10) + 9;
}
var actualHeight = loadedContent.outerHeight(true) + 5;
loadedContent.css("overflow", "visible");
content.height(actualHeight + innerHeightDiff);
contentLeft.height((actualHeight + innerHeightDiff) - sideTopBottomSize);
contentRight.height((actualHeight + innerHeightDiff) - sideTopBottomSize);
wrapper.height(actualHeight + innerHeightDiff + outerHeightDiff);
colorbox.height(actualHeight + innerHeightDiff + outerHeightDiff + wrapperHeightDiff);
colorbox.css("visibility", "visible");
} catch (e) { }
if (continueResizing === true) {
setTimeout(resizeHtml, resizeHtml.updateInterval);
}
}
$(document).bind('cbox_open', function() {
$("#colorbox").css("visibility", "hidden");
});
$(document).bind('cbox_complete', function() {
var iframe = $("#cboxIframe");
var content = $("#cboxLoadedContent");
continueResizing = true;
if (iframe.length > 0 && window.top == window) {
setTimeout(resizeLightbox, resizeLightbox.updateInterval);
} else if (content.children(":not(iframe), :not(img)").length > 0) {
setTimeout(resizeHtml, resizeHtml.updateInterval);
} else {
$("#colorbox").css("visibility", "visible");
}
});
$(document).bind('cbox_cleanup', function() {
continueResizing = false;
});
resizeLightbox.updateInterval = 100;
resizeHtml.updateInterval = 100;
$.fn.colorbox.standardOptions = {
login: {
href: URLUtil.resolveUrl("~/h/login"),
title: "Welcome to Rogers On Demand Online!",
height: 330,
width: 515,
scrolling: false,
iframe: true,
transition: "none"
},
userMessage: {
title: "Welcome back!",
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 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: "200px",
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);
});
};
RJS.hotkeySequence = function(charOne, charTwo, callback) {
var k1 = charOne.toUpperCase().charCodeAt(0),
k2 = charTwo.toUpperCase().charCodeAt(0),
isCtrlPressed = false,
isInSequence = false,
CTRL = 17;
$(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;
}
});
}
})(jQuery);

/*************************** ddroundies.js ***************************/

/*************************** jcarousellite_1.0.1.js ***************************/

/*************************** jquery.easing.1.3.js ***************************/

/*************************** jquery.mask.js ***************************/

/*************************** jquery.validate.js ***************************/

/*************************** rjs.ad.js ***************************/
RJS.Player = {
"title":null
, "returnTitle":null
, "player":null
, "wrapper":null
, "ad":null
, "shrink":function() {
var newWidth = 615;
var newHeight = 345;
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();
}
, "grow":function() {
var newWidth = 712;
var newHeight = 399;
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();
}
, "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(banners) {
if (!tile) {
tile = RJS.AdManager.count();
}
function render(banner) {
var ad = RJS.AdManager.get(banner.region);
var oldUrl = ad.toQueryParams();
var newUrl = new RJS.Ad(banner.region, {
"autoLoad": false
, "iframe": {
"src": banner.src, "frameborder":0, scrolling:"no"
}
}).toQueryParams();
if (oldUrl.params.pos) {
newUrl.params.pos = oldUrl.params.pos;
}
newUrl.params.tile = ++tile;
ad.options.iframe.src = ad.toQueryString(newUrl);
ad.renderTag();
};
if (Object.isArray(banners)) {
banners.each(render);
} else {
render(banners);
}
}
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 = $("#outer_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
c.find(".average").hide();
var userRating = c.find(".user");
var cursorPos = ev.pageX - c.offset().left;
userRating.show();
var ratingDOM = userRating.get(0);
if (typeof ratingDOM === "undefined")
return;
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");
if (rating != null) {
rating = parseInt(rating, 10);
switch (rating) {
case 1:
userRating.get(0).className = 'rating user one';
break;
case 2:
userRating.get(0).className = 'rating user two';
break;
case 3:
userRating.get(0).className = 'rating user three';
break;
case 4:
userRating.get(0).className = 'rating user four';
break;
case 5:
userRating.get(0).className = 'rating user five';
break;
default:
userRating.get(0).className = 'rating user';
userRating.hide();
avgRating.show();
break;
}
} else {
userRating.get(0).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(location, "Please sign in to rate this video", "rate");
return;
}
var c = $(this); //context
var userRating = c.find(".user").attr("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, createdDate: 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("Comments (<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;
}
if (RJS.User.isSignedIn() === false) {
RJS.User.signIn(location, "Please sign in to reply");
return;
}
var commentContainer = $(this).closest(".comment");
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;
}
});
}
//*** ADD TO FAVORITES ***
$("a.favorite.add").live("click", 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(location, "Please Sign In to Use This Feature");
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
$(".addEpisode").live("click", function() {
if (RJS.User.userInfoLoaded !== true) {
return false;
}
if (!favoritesEnabled) {
RJS.Toast("", RJS.settingDisabledCopy, 5000);
return false;
}
if (RJS.User.isSignedIn() === false) {
return;
}
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");
}
});
});
});
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",
title: "Rogers On Demand Online Community Setup",
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 });
}
RJS.Community = {
flag: function(commentID) {
$("#" + commentID).addClass("flagged");
},
add_PlaylistUpdated: function(playlistUpdatedHandler) {
RJS.Event.bind("community.playlistUpdated", playlistUpdatedHandler);
}
}
})(jQuery);

/*************************** 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) {
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); }
};
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("Failed to load viewstate.") !== -1) {
window.location.reload();
}
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();
prm.add_beginRequest(function(sender, args) {
jQuery(".Loading").show();
});
prm.add_endRequest(function(sender, args) {
jQuery(".Loading").hide();
});
})();

/*************************** rjs.jq.spots.js ***************************/
jQuery(document).ready(function($) {
var supportedBrowser = ($.browser.msie && $.browser.version >= 7) || $.browser.safari || $.browser.mozilla;
if (!supportedBrowser)
$("#browserNotSupported").show();
// 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());
});
}
setTimeout(loadDocks, 1);
var hoverIntentTime = 200;
var menuItems = $(".menu > li");
var menuTabs = $("#headerWrap .inner > div");
var anchorDocks = $("#NavDocks").children("a");
var contentDocks = $("#NavDocks").children("div");
var restOfPage = $('#bdy, #header, li.home');
var selectWraps = $("select");
selectWraps.each(function() {
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();
});
function showNavTray() {
RJS.Tooltip.hideAll();
var index = menuItems.index(this);
var currentTab = anchorDocks.eq(index - 1).show();
var currentContent = contentDocks.eq(index - 1).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);
}
return false;
}
function hideNavTray(ev) {
if (ev) {
var index = anchorDocks.index(ev.target);
if (index > -1) return true;
index = menuItems.index(ev.target);
if (index > -1) return true;
index = contentDocks.index(ev.target);
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).mouseover(function() {
RJS.Timer.add('hide', 'hide', hideNavTray, 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', '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);
});

/*************************** rjs.jq.tabs.js ***************************/
(function rjsTabs($) {
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);
}
}
if (typeof RJS === 'undefined') window.RJS = {};
RJS.Tabs = {};
RJS.Tabs.activateTab = activateTab;
// 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 === 0 && typeof id === "function") {
tabEventListeners.generalListeners.push(id);
}
if (tabEventListeners.specificlisteners[id] === undefined) {
tabEventListeners.specificlisteners[id] = [];
}
tabEventListeners.specificlisteners[id].push(handler);
};
$(document).ready(function() {
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;
}
}
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;
}
}
});
function init() {
// Prefetch tabs & tab boxes to speed up access to them when the user clicks a tab
tabBoxes = $(".tabbed_box");
allTabs = tabBoxes.find(".tabs");
sideLinks = $("#two-col .section .links a[rel]");
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 (location.hash) {
var hash = location.hash.gsub("#_", "").gsub("#", "");
findAndSetTab(hash);
}
}
init();
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(init);
});
})(jQuery);

/*************************** 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.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) {
if (val < 0 || val > options.totalPages) return;
if (page == val) return;
page = val;
build();
document.fire('Pager:pageClick', { id: id, page: page });
}
var setTotalPages = function(i) {
options.totalPages = i;
if (page > options.totalPages || page === 0)
setPage(options.totalPages);
else 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}\
<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.thumbUrl}"/></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.name}</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}\
<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.thumbUrl}"/></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="#" 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.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}\
<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.thumbUrl}"/></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="#" 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.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}\
<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.thumbUrl}"/></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="#" class="favorite add fltrght" rel="{$T.id}"></a>\
</div>\
<h2 class="video-title"><a href="{$T.playUrl}">{$T.name}</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}\
<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.thumbUrl}"/></a>\
</div>\
<div class="util">\
<ul class="iconGroup">\
<li><span class="fltlft icon movie"></span></li>\
<li class="entitle"><div class="entitlement {$T.premiumStatus}" rel="{$T.entitlement}"></div></li>\
</ul>\
<a href="#" class="favorite add fltrght" rel="{$T.id}"></a>\
</div>\
<h2 class="video-title"><a href="{$T.playUrl}">{$T.name}</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}\
<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.thumbUrl}"/></a>\
</div>\
<div class="util">\
<ul class="iconGroup">\
<li><span class="fltlft icon movie"></span></li>\
<li class="entitle"><div class="entitlement {$T.premiumStatus}" rel="{$T.entitlement}"></div></li>\
</ul>\
<a href="#" 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.boxArtImageUrl}" alt="" title="" class="poster" />\
<div class="video-wrap">\
<div class="video">\
<ul>\
<li>\
<div class="thumb">\
{$T.promo}\
<a href="{$T.playUrl}" rel="{$T.infoUrl}"  class="play">play video</a>\
<a class="fltlft" href="{$T.playUrl}" rel="{$T.infoUrl}"><img src="{$T.thumbUrl}" alt="" title="" /></a>\
</div>\
<div class="util">\
<ul class="iconGroup">\
<li><span class="fltlft icon movie"></span></li>\
<li class="entitle"><div class="entitlement {$T.premiumStatus}" rel="{$T.entitlement}"></div></li>\
</ul>\
<a href="#" class="favorite add fltrght" rel="{$T.id}"></a>\
</div>\
<h2 class="video-title"><a href="{$T.playUrl}" >{$T.name}</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}\
<a href="{$T.playUrl}" rel="{$T.infoUrl}"  class="play">play video</a>\
<a class="fltlft" href="{$T.playUrl}" rel="{$T.infoUrl}"><img src="{$T.thumbUrl}" 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="#" class="favorite add fltrght" rel="{$T.id}"></a>\
</div>\
<h2 class="video-title"><a href="{$T.playUrl}" >{$T.name}</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}</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.name}</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.createdDate}">{$T.createdDate}</span></p>\
<p class="commentBody">{$T.comment}</p>\
<p class="deletedCommentBody">This comment violated our Terms of Service and has been removed.</p>\
</div>')
};

/*************************** 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) {
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);
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('Error occured while trying to retrieve information. Try again later.');
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 (element == null)
return;
var tooltip = getTooltip(element);
if (!element.id) {
element.id = 'trigger-' + triggerCounter++;
}
var o = self.options;
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.
$(o.context).observe(o.show, showTooltip)
.observe(o.hide, hideTooltip);
} else if (o.element != null) {
$(o.element).observe(o.show, showTooltip)
.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) {
var d = e.getDimensions();
var o = e.cumulativeOffset();
var retVal = (m.y > o.top) && (m.y < (o.top + d.height)) && (m.x > o.left) && (m.x < (o.left + d.width));
return retVal;
};
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);
}
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();
$(".userInfo").remove();
header.after(content);
content.fadeIn(50);
self.userInfoLoaded = true;
if (/\/user$/.match(window.location.href) || window.location.href.indexOf("/user/") > -1) {
content.find("a:contains('Join')").addClass("active");
} else if (/\/account$/.match(window.location.href) || window.location.href.indexOf("/account/") > -1) {
content.find("a:contains('My Profile')").addClass("active");
} else if (/\/help$/.match(window.location.href) || window.location.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);
}
self.applyUserSettingsToAssets();
RJS.Event.trigger("user.infoLoaded");
};
self.reloadUserInfo = function(returnUrl) {
self.userInfoLoaded = false;
try {
$.fn.colorbox.close();
} catch (e) { }
RJS.Event.trigger("user.loggingIn", returnUrl);
var url = URLUtil.resolveUrl("~/h/userinfo");
var header = null;
if (topHeader.length > 0) {
header = topHeader.find("h1.page-title");
$(".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]);
}
});
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;
RJS.Event.trigger("user.infoLoaded");
}
});
if (topHeader.length > 0) {
header = topHeader.find("h1.page-title");
}
};
self.signOut = function() {
var oldUserInfo = $(".userInfo");
var request = $.post(URLUtil.resolveUrl("~/h/userinfo/true"), {}, function(html) {
window.location = URLUtil.resolveUrl("~/");
});
return false;
};
self.signIn = function(returnUrl, title, verb) {
var c = {};
$.extend(c, loginColorboxOptions);
if (typeof title !== "undefined" && $.trim(title).length > 0) {
c.title = title;
}
if (typeof returnUrl !== "undefined") {
c.href = URLUtil.resolveUrl("~/h/login?ReturnUrl=" + escape(returnUrl));
}
if (typeof verb !== "undefined") {
if (c.href.indexOf("?") > -1) {
c.href = c.href.split("?")[0] + "?verb=" + verb + "&" + c.href.split("?")[1]
} else if (c.indexOf("#")) {
c.href = c.href.split("#")[0] + "?verb=" + verb + c.href.split("#")[1]
} else {
c.href = c.href + "?verb=" + verb
}
}
$.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;
$(".entitlementTT").remove();
$("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 logged in 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 (RJS.User.favorites.length > 0) {
$(".playlistAssetCount").text(" (" + RJS.User.favorites.length + ")");
}
$(".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() {
topHeader = $("#header");
loadUserInfo();
$("a.asyncSignout", topHeader.get(0)).live('click', function signoutClick(e) {
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.signedIn) {
try {
if (this.href.indexOf("#_comments") > -1) {
self.signIn(this.href, this.title);
} else {
self.signIn(window.location, this.title);
}
} catch (e) { }
e.preventDefault();
return false;
}
});
$("a.loginLink").live('click', function loginLinkClick(e) {
if (e.button == 0 && !self.signedIn) {
self.signIn();
e.preventDefault();
return false;
}
});
});
}
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 $ = 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();
}
};
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",
onkeyup: false,
onfocusout: 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) {
if (trim(error.text()) === "") return;
/* Date of Birth requires special handling because it groups multiple fields
Check if validating DoB, and handle it accordingly, or use
standard error handling otherwise.
*/
var parent = element.parent("#DateofBirth");
if (parent.length === 0) {// Non-DoB Wrapping
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);
} else {// DoB Wrapping
var valWrap = parent.find(validationSelector);
if (valWrap.length === 0) {
valWrap = validationHtml.clone();
var lastInput = parent.find("input:last");
lastInput.next().after(valWrap).after("<br />");
valWrap.append(error);
} else {
if (containsError(valWrap, $(error).text())) {
return;
}
valWrap.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
/*,
*/
};
function unhighlight(element, errorClass) {
if ($("form").validate().numberOfInvalids() === 0) {
$(".errors").hide();
}
var valWrap = $(element).parent().find(validationSelector);
if (valWrap.length === 0)
return;
// Date of Birth requires special handling because it groups multiple fields
// Check if validating DoB, and handle it accordingly, or use
// standard error handling otherwise.
// standard error handling otherwise.
var dob = valWrap.parent("#DateofBirth");
if (dob.length === 0) {
var isValid = validator.check($(element));
if (isValid) {
valWrap.remove();
$(element).removeClass(errorClass);
}
} else {
var invalids = valWrap.find('p.' + errorClass);
if (invalids.length === 1) {
var elem = $('#' + invalids.attr('htmlfor'));
var isValid = elem.validate().check(elem);
}
if (invalids.length === 0 || isValid === true) {
valWrap.remove();
$(element).removeClass(errorClass);
} else {
invalids = valWrap.find('p.' + errorClass + ':hidden');
invalids.remove();
}
}
}
var validator;
var settings;
self.getValidator = function() { return validator; };
self.register = function register(form, options) {
// The "form" argument is optional (only the options argument is required). Correct the
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, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{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) {
return value.match(/(^[a-zA-Z][0-9][a-zA-Z](-| )?[0-9][a-zA-Z][0-9]$)|(\s*)/);
}, '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.");
$.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();
prm.add_initializeRequest(function(sender, args) {
if (validator.cancelSubmit || RJS.Validate.cancelled || $(args.get_postBackElement()).hasClass("cancel")) {
validator.cancelSubmit = true;
RJS.Validate.cancelled = true;
return true;
}
RJS.Validate.cancelled = false;
var isValid = validator.form();
if (!isValid) {
args.set_cancel(true);
}
});
}
}
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 self.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 = {};
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);
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) {
element.update();
var requestListing = function(params) {
var hash = $H(filters).update(params);
if (loading) {
loading.setStyle({ display: "block" });
}
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() {
if (loading) {
loading.setStyle({ display: "none" });
}
if (errorContent) {
errorContent.setStyle({ display: "block" });
}
window.console && console.log('failure');
};
var exception = function(a, b) {
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) || pageCount === 0) return;
if (!pager) pager = RJS.TBPager(id, pagerRoot, { totalPages: pageCount });
else pager.setTotalPages(pageCount);
};
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 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 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) {
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);
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 (pagerRoot) buildPager(Math.ceil(json.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) {
if (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) {
if (!assets) return;
element.update(listBuilder.buildString(assets));
//rewireTooltips(element);
};
document.observe('Pager:pageClick', function(evt) {
if (evt.memo.id == id) {
pageNo = evt.memo.page - 1;
requestMedia(gotListing)
}
});
document.observe('Video#' + id + ':filter', function(evt) {
filters[evt.memo.type] = evt.memo.value;
setActive(evt.memo.type, evt.memo.value);
requestMedia(gotListing);
});
if (outer) {
buildFilter("filter");
buildFilter("sort");
buildFilter("layout");
buildFilter("currentRun");
buildFilterDDL("season");
buildFilterDDL("language");
buildFilterDDL("sort");
buildFilterDDL("team");
}
//requestMedia(gotListing);
return { setHandler: function(url) { setHandler(url); requestMedia(gotListing); }, load: function() { requestMedia(gotListing); } };
}

/*************************** rjs.welcome.js ***************************/
/// <reference path="http://jqueryjs.googlecode.com/files/jquery-1.3.2-vsdoc2.js" />
; (function($) {
var c = RJS.Cookie,
firstVisit = "FirstVisit",
href = location.href;
if ((c.get(firstVisit) !== "no" && href.indexOf("/h/") === -1 && href.indexOf("/handlers/") === -1 && href.indexOf("/user") === -1 && top.location == location) && href.indexOf("/login") === -1 || getQueryString("showWelcome") === "true") {
var firstRun = true;
$(function() {
$colorbox = $("#colorbox");
$.fn.colorbox({
href: URLUtil.resolveUrl("~/h/welcome"),
title: "",
height: 485,
width: 610,
scrolling: false,
iframe: true,
onLoad: function() {
if (firstRun === true) {
$colorbox.addClass("welcome");
firstRun = false;
}
},
onCleanup: function() {
setTimeout(function() { $colorbox.removeClass("welcome"); }, 1);
}
});
});
}
c.set(firstVisit, "no", new Date(9999, 0, 1));
})(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($) {
var swapTitleToTooltip = function(elem) {
if ($(elem).attr('title')) {
$(elem).attr("altTitle", $(elem).attr('title'));
$(elem).attr('title', '');
}
return $(elem).attr("altTitle");
};
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'
}));
}
var regularContext = $("#middle, #right:has(#landing,.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',
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({
selector: 'a.infoAlt',
position: 'top',
baseClass: 'infoAlt_hover',
direction: 'rightTopClass',
autoAdjust: true,
ignoreBottomContextBoundary: true,
ignoreTopContextBoundary: true,
adjustLeft: 0,
instanceName: 'infoAlt'
});
RJS.Tooltip.init({
selector: 'a.ccAlt, a.cc',
position: 'top',
direction: 'rightTopClass',
content: '<span>Closed captioning</span> available.',
instanceName: 'ClosedCaptioning'
});
RJS.Tooltip.init({
selector: 'a.hdAlt, a.hd',
position: 'top',
direction: 'rightTopClass',
content: 'This video is available in <span>High Definition</span>.',
instanceName: 'High Definition'
});
RJS.Tooltip.init({
selector: 'a.add',
position: 'top',
direction: 'rightTopClass',
content: 'Add this video to your playlist',
instanceName: 'AddToFavorite',
hoverIntentDelay: 600
});
RJS.Tooltip.init({
selector: 'a.added',
position: 'top',
direction: 'rightTopClass',
content: 'This video is on your playlist. Click again to view and modify your playlist',
instanceName: 'AddedToFavorite',
hoverIntentDelay: 600
});
RJS.Tooltip.init({
selector: '.cbVerify',
position: 'top',
direction: 'rightTopClass',
content: 'This will verify the information you have entered.',
instanceName: 'verify',
hoverIntentDelay: 600
});
RJS.Tooltip.init({
selector: '.cbLater',
position: 'top',
direction: 'rightTopClass',
content: 'No problem, you can skip the verification for now.',
instanceName: 'verifyLater',
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
});
}
RJS.Tooltip.init({
selector: '.liveText',
position: 'top',
direction: 'rightTopClass',
content: 'Text &#39;SAY&#39; &#43; your comment to 101010',
instanceName: 'sendNow',
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
});
RJS.Tooltip.init({
selector: 'a.share',
position: 'top',
direction: 'rightTopClass',
content: 'Share this video.',
instanceName: 'AddedShare',
hoverIntentDelay: 600
});
RJS.Tooltip.init({
selector: 'a.titleInfo',
baseClass: 'assetInfo_hover',
position: 'bottom',
direction: 'leftBottomClass',
nudgeTop: 20,
adjustLeft: -203,
instanceName: 'TitleInfo'
});
RJS.Tooltip.init({
selector: 'a.FindbytitleInfo, div.FindbytitleInfo',
adjustLeft: -20,
adjustTop: 0,
instanceName: 'FindbytitleInfo'
});
RJS.Tooltip.init({
selector: 'a.assetInfoImg',
baseClass: 'assetInfo_hover',
position: 'bottom',
direction: 'leftBottomClass',
nudgeTop: 20,
adjustLeft: -208,
instanceName: 'AssetInfoImg'
});
RJS.Tooltip.init({
selector: 'a.assetInfo',
adjustLeft: -20,
adjustTop: 0,
autoAdjust: true,
instanceName: 'assetInfo'
});
var contentInfoOptions = {
autoAdjust: true,
baseClass: 'contentInfo_hover',
content: swapTitleToTooltip
};
RJS.Tooltip.init($.extend({}, { selector: 'a.contentInfo' }, contentInfoOptions));
RJS.Tooltip.init($.extend({}, { selector: 'a.contentInfoLink' }, contentInfoOptions));
var contentInfoClickOptions = { hide: 'click' };
$.extend(contentInfoClickOptions, contentInfoOptions);
RJS.Tooltip.init($.extend({}, { selector: 'a.contentInfoLink' }, contentInfoClickOptions));
RJS.Tooltip.init($.extend({}, { selector: 'a.contentInfoThik', nudgeTop: 20, direction: 'rightBottomClass' }, contentInfoClickOptions));
RJS.Tooltip.init($.extend({}, { selector: 'a.contentInfoThik2', nudgeTop: 60, nudgeLeft: 100, direction: 'leftTopClass' }, contentInfoClickOptions));
RJS.Tooltip.init($.extend({}, { selector: 'a.contentInfoThik3', nudgeBotom: 100, nudgeLeft: 100, direction: 'leftTopClass' }, contentInfoClickOptions));
RJS.Tooltip.init({
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'
});
});

/*************************** util.js ***************************/
//****************************************************************************
// Copyright (C) thePlatform for Media, Inc. All Rights Reserved.
//****************************************************************************
////// UTIL FUNCTIONS ////////////
// 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 illegalGeoCode() {
var $ = jQuery;
$("#player").hide();
$("#player-wrap").append('<div class="playerMessage Video">\
<div class="message">\
<p>We\'re sorry, Rogers On Demand Online video can only be viewed within Canada. </p>\
<p>\
If you\'re within Canada and believe you have received this message in error \
please <a href="' + URLUtil.resolveUrl('~/about/contact#Eligibility') + '" class="genericLink" target="_top">click here</a>.\
</p>\
</div>\
</div>');
}
var overlayLastLoaded = null;
// function called when video has ended / restarted
function flashShowOverlay(assetId) {
var overlay = jQuery(".overlay");
var video = jQuery("#videoOverlay");
var p = RJS.Player.player;
if (p && p.flashResize) {
var newWidth = 615;
var newHeight = 345;
p.flashResize(newWidth, newHeight);
p.style.width = newWidth + "px";
p.style.height = newHeight + "px";
RJS.Player.wrapper.style.marginLeft = "0";
}
video.fadeIn();
overlay.show();
jQuery("h2.return").hide();
if (typeof assetId !== 'undefined' && (overlayLastLoaded === null || overlayLastLoaded < new Date(new Date().setSeconds(-10)))) {
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.");
}
RJS.Player.ad && RJS.Player.ad.fadeIn();
}
// Dim the Lights control
function flashDimLight() {
var h = jQuery("#main").height();
var h2 = jQuery("#footer-wrap").height();
var dim = jQuery("#lightDimmer");
var dimTop = jQuery("#lightDimmerTop");
var both = jQuery("#lightDimmerTop, #lightDimmer, #lightDimmerFoot");
var chanInfo = jQuery(".imgWrap img, #selector select, .titlebar h4, .titlebar p, .titlebar a, .fifaChannel img, .rated");
jQuery("#main, #footer-wrap").addClass('dimMain');
jQuery(dim).height(h + h2);
jQuery(both).css('opacity', 0.8);
jQuery(both).fadeIn('slow');
jQuery(chanInfo).fadeTo("slow", 0.2);
jQuery(".titlebar").addClass("dimLight");
jQuery(".channelSkin").fadeTo("slow", 0.1);
jQuery(".tandemAd").css('opacity', 1);
}
function flashRaiseLight() {
var chanInfo = jQuery(".imgWrap img, #selector select, .titlebar h4, .titlebar p, .titlebar a, .fifaChannel img, .rated");
var both = jQuery("#lightDimmerTop, #lightDimmer, #lightDimmerFoot");
jQuery(".tandemAd").css('opacity', 1);
jQuery(both).fadeOut();
jQuery(".titlebar").removeClass("dimLight");
jQuery(chanInfo).css('opacity', 1);
jQuery(".channelSkin").fadeTo("slow", 1.0);
}
function flashHideOverlay() {
var newWidth = 712;
var newHeight = 399;
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;
}
}

