var UberPlayer = function () {
	var $S = CBC.SETTINGS;
	var $U = CBC.UTIL;
	var $E = CBC.EVENT;
	var $D = CBC.DOM;
	var $ = $U.getElementsById;
	var _this;
	var currentCategory = {};
	var _previousCategory;
	var _currentSortField;
	var site = "cbc.news.ca";
	var _adPlaying = false;
	var _releaseQueue = {};
	var _pureMax = 500;
	var currentRelease = {};
	var _previousRelease;
	var _currentSection="shows";
	var allCategories = [];
	var allReleases = [];
	var _feedRoot = "http://cbc.feeds.theplatform.com/ps/JSON/PortalService/2.2/";
	var page_data = {
		pageMax: 6,
		currentPage: 1,
		totalPages: 1,
		onclickfunc:'CBC.APP.UberPlayer.changePage',
		container:'pagination'
	};
	var _breadcrumbObject = [];
	var deepLinkRelease = {};
	var defaultSponsorImage = "/imgs/bg-shows.jpg";
	var currentSponsorImage = "";
	var currentAdCategory = "";
	var playerMode = "";
	var showFeatures = true;
	// UI vars
	var _maxDescLength = 100; // maximum length of description to show
	var _extendedDescLength = 145; // maximum length of description to show if no expiry date appears (1 extra line available)
	var _maxExpiryHrs = 168; // do not display expiry information if higher than this number
	var _defaultThumbPath = '/video/imgs/thumb-default.gif';
	// Search vars
	var _googleSearchBaseUrl = '/search/cbc?json=true&sitesearch=www.cbc.ca/video/watch&';
	var _searchResultsPerPage = 9; // max search items to display per page
	var _searchStartIndex; // stores the position in search results the user is currently at
	var _searchQuery; // search keywords
	var _searchFilter = ''; // holds current search filter
	var _searchObjects = [];
	// Templates
	$S.setVal('tpl_cat_item',new $U.Template('<li id="#{id}"><a href="#{link}">#{label}</a></li>'));
	$S.setVal('tpl_library_clip', new $U.Template('<div id="#{id}" class="clip">#[liveState: {not:<div class="head clearfix"><p class="date">#{date}</p><p class="dur">#{duration}</p></div>||now:<div class="head livenow clearfix">Live Now</div>||later:<div class="head livelater clearfix"><em>Live</em> #{liveDate} at #{liveTime}</div>}]<a href="#{link}" #{anchorAttrib}><img src="#{thumbnailURL}" alt="#{label} - #{title}" width="220" height="124" /><span class="id">#{label}</span><span class="title">#{title}</span><span class="desc">#{description}<em>#{expiry}</em></span></a></div>'));
	$S.setVal('tpl_link',new $U.Template('<a href="#{link}">#{label}</a>'));
	$S.setVal('tpl_page_step',new $U.Template('<a href="#" class="#{prevnext}" onclick="return #{onclickfunc}(#{pg});">#{label}</a>'));
	$S.setVal('tpl_page_step_disabled',new $U.Template('<a href="#" class="#{prevnext} disabled" onclick="return false;">#{label}</a>'));
	$S.setVal('tpl_page_num',new $U.Template('<a href="#" class="pg #[active: {false:||true:active}]" onclick="return #{onclickfunc}(#{pg});">#{pg}</a>'));
	return {
		init: function (initObject) {
			_this = this;
			var feedPID = initObject.feedPID;
			SWFAddress.addEventListener(SWFAddressEvent.CHANGE, this.handleLocationChange);
			tpController.addEventListener("OnMediaStart", this.OnMediaStart);			
			tpController.addEventListener("OnMediaComplete", this.OnMediaComplete);
			tpController.addEventListener("OnReleaseEnd", this.OnReleaseEnd);		
			var swfa_val = SWFAddress.getValue();
			if (swfa_val.length > 1) {
				if (swfa_val == "/Search") {
					this.switchLibraryTab('search');
					this.switchMode("features");
					$('bbox').src = "bigbox.html?shows";
				} else {
					swfa_val=this.replaceAmpersands(swfa_val);
					swfa_val=this.replaceQuestionMarks(swfa_val);
					this.deepLink(this.replaceUnderscores(swfa_val));
				}
			} else {
				this.deepLink(initObject.categoryName);
			}
		},

		OnReleaseEnd: function(e) {
			deepLinkRelease = {};
		},

		OnMediaStart: function(e) {
			for (var i = 0, length = e.data.baseClip.banners.length; i < length; i++) {
				var bannerRegion = e.data.baseClip.banners[i].region;
				var bannerURL = e.data.baseClip.banners[i].src.replace("pfadx", "adi");
				var bannerIFrame = document.getElementById(bannerRegion);
				if (bannerIFrame) {
					bannerIFrame.src = bannerURL;
				}
			}
			if (e.data.baseClip.isAd) {
				_adPlaying = true;
			} else {
				_adPlaying = false;
			}
		},

		OnMediaComplete: function (e) {
			_adPlaying = false;
			if (!_this.isEmpty(_releaseQueue)) {
				_this.playRelease(_releaseQueue.URL, _releaseQueue.ID, true);
				_releaseQueue = {};
			}
		},

		setBigBoxCategory : function (category) {
			if (playerMode=="features" || playerMode=="") {
				document.getElementById('bbox').src = "bigbox.html?"+category;
			}
		},

		deepLink: function (fullCategoryName) {
			var fullCategoryNameArray = fullCategoryName.split("");
			var categoryForBB='';
			if (fullCategoryNameArray[0]=='/') {
				categoryForBB=fullCategoryName.substring(1, fullCategoryName.length);
			} else {
				categoryForBB=fullCategoryName;
			}
			var categoryForBBArray = categoryForBB.split('/');
			if (categoryForBBArray.length>1) {
				categoryForBB = categoryForBBArray[0].toLowerCase();
			} else {
				categoryForBB = categoryForBB.toLowerCase();
			}
			if (categoryForBB=='shows') {
				this.setBigBoxCategory(categoryForBB);
				site = "cbc.ent.ca";
				defaultSponsorImage = "imgs/bg-shows.jpg";
				_currentSection="shows";
			}
			if (categoryForBB=='news') {
				this.setBigBoxCategory(categoryForBB);
				site = "cbc.news.ca";
				defaultSponsorImage = "imgs/bg-news.jpg";
				_currentSection="news";
			}
			if (categoryForBB=='sports') {
				this.setBigBoxCategory(categoryForBB);
				site = "cbc.sports.ca";
				defaultSponsorImage = "imgs/bg-sports.jpg";
				_currentSection="sports";
			}
			var fullCategoryArray = this.createInitCategory(fullCategoryName);
			this.switchLibraryTab(fullCategoryArray[0].toLowerCase(), fullCategoryArray[0]);
			var categoryArray = [];
			categoryArray[0] = fullCategoryArray[0];
			_currentSection = fullCategoryArray[0].toLowerCase();
			this.getCategoriesByTitle(categoryArray, fullCategoryArray);
			var id = fullCategoryName.match( /ID=[0-9]+/g );
			var hasId = ( id != null );
			if (showFeatures && !hasId)
			{
				var swf = swfobject.getObjectById("features_id");
				if (swf)
				{
					if (swf.setCategoryId != null)
					{
						swf.setCategoryId(fullCategoryArray[0].toString());
					}
				}
			}
			if( hasId )
			{
				var r = this.findRelease( id[0].substr(3) );
				if( r )
				{
					if (r.ID != null && r.URL != null)
					{
						this.playRelease(r.URL, r.ID);
					}
				}
			}
		},

		createInitCategory: function (categoryName) {
			//categoryName = categoryName.toLowerCase();
			if (categoryName.lastIndexOf("ID=") > 0) {
				this.switchMode("player");
				var id = categoryName.match( /ID=[0-9]+/g );
				deepLinkRelease.ID = id[0].substring(3, id[0].length);
				categoryName = categoryName.substring(0, categoryName.lastIndexOf("ID="));
			} else {
				this.switchMode("features");
				deepLinkRelease.ID = 0;
			}
			if (categoryName.charAt(0) == "/") {
				categoryName = categoryName.substring(1, categoryName.length);
			}
			if (categoryName.charAt(categoryName.length - 1) == "/") {
				categoryName = categoryName.substring(0, categoryName.length - 1);
			}
			return categoryName.split("/");
		},

		handleLocationChange: function (e) {
			switch(e.path) {
				case "/":
					CBC.APP.UberPlayer.deepLink('Shows');
					break;
				case "/Shows":
					CBC.APP.UberPlayer.deepLink('Shows');
					break;
				case "/News":
					CBC.APP.UberPlayer.deepLink('News');
					break;
				case "/Sports":
					CBC.APP.UberPlayer.deepLink('Sports');
					break;
				case "/Search":
					/* ie 6 issue
					CBC.APP.UberPlayer.switchLibraryTab('search'); */
					break;
				case "/Comments":
					CBC.APP.UberPlayer.switchLibraryTab('comments');
					CBC.APP.UberPlayer.renderComments();
					break;
				default:
					break;
			}
			//condition for comments
			if (e.path != "socialcomments") SWFAddress.setTitle("CBC - Videos - "+e.path);
		},

		getCategoriesByTitle: function (categoryArray, fullCategoryArray) {
			this.displayLoading(true);
			var newCategoryArray = categoryArray.join("/");
			var categoryRequestString = [];
			categoryRequestString.push(_feedRoot);
			categoryRequestString.push('getCategoryList?');
			categoryRequestString.push('PID=');
			categoryRequestString.push(feedPID);
			categoryRequestString.push('&');
			categoryRequestString.push('field=ID&');
			categoryRequestString.push('field=title&');
			categoryRequestString.push('field=parentID&');
			categoryRequestString.push('field=description&');
			categoryRequestString.push('field=customData&');
			categoryRequestString.push('query=FullTitles|');
			categoryRequestString.push(newCategoryArray);
			categoryRequestString.push('&');
			categoryRequestString.push('customField=backgroundImage&');
			categoryRequestString.push('customField=Keywords&');
			categoryRequestString.push('customField=IsDynamicPlaylist&');
			categoryRequestString.push('customField=GroupLevel&');
			categoryRequestString.push('customField=GroupOrder&');
			categoryRequestString.push('customField=Account&');
			categoryRequestString.push('customField=CreatedAfter&');
			categoryRequestString.push('customField=CreatedBefore&');
			categoryRequestString.push('customField=Genre&');
			categoryRequestString.push('customField=Show&');
			categoryRequestString.push('customField=SortField&');
			categoryRequestString.push('customField=MaxClips&');
			categoryRequestString.push('customField=SeasonNumber&');
			categoryRequestString.push('customField=Sport&');
			categoryRequestString.push('customField=Region&');
			categoryRequestString.push('customField=Event&');
			categoryRequestString.push('customField=People&');
			categoryRequestString.push('customField=CBCPersonalities&');
			categoryRequestString.push('customField=Aired&');
			categoryRequestString.push('customField=AudioVideo&');
			categoryRequestString.push('customField=BylineCredit&');
			categoryRequestString.push('customField=Characters&');
			categoryRequestString.push('customField=ClipType&');
			categoryRequestString.push('customField=EpisodeNumber&');
			categoryRequestString.push('customField=LiveOnDemand&');
			categoryRequestString.push('customField=Organizations&');
			categoryRequestString.push('customField=Producers&');
			categoryRequestString.push('customField=Segment&');
			categoryRequestString.push('customField=Sub-Event&');
			categoryRequestString.push('customField=SortOrder&');
			categoryRequestString.push('customField=AdCategory&');
			categoryResponse = function (response) {
					_this.displayLoading(false);
					if (response.items.length) {
						categoryArray.push(fullCategoryArray[categoryArray.length]);
						currentCategory = new _this.category(response.items[0]);
						_this.editBreadcrumbObject();
						_this.pushToAllCategories(currentCategory);
						if ((categoryArray.length < fullCategoryArray.length + 1) && (response.items.length > 0)) {
							_this.getCategoriesByTitle(categoryArray, fullCategoryArray);
						} else { if (_breadcrumbObject.length > 1) {
							_this.getCategoriesByID(_breadcrumbObject[_breadcrumbObject.length - 2].ID, true);
						}
						_this.getCategoriesByID(_breadcrumbObject[_breadcrumbObject.length - 1].ID, false);
					}
				} else {
					_this.deepLink("Shows");
				}
			}
			var categoryRequest = new JSONRequest(categoryRequestString.join(''), "categoryResponse");
			categoryRequest.send();
		},

		getCategoriesByID: function (categoryID, isSideBar) {
			this.switchFilter('libraryfilters',$('fFeatured'));
			this.displayLoading(true);
			currentCategory = this.findCategory(categoryID);
			currentSponsorImage = currentCategory.backgroundImage;
			currentAdCategory = currentCategory.AdCategory;
			var categoryRequestString = [];
			categoryRequestString.push(_feedRoot);
			categoryRequestString.push('getCategoryList?');
			categoryRequestString.push('PID=');
			categoryRequestString.push(feedPID);
			categoryRequestString.push('&');
			categoryRequestString.push('field=ID&');
			categoryRequestString.push('field=title&');
			categoryRequestString.push('field=parentID&');
			categoryRequestString.push('field=description&');
			categoryRequestString.push('field=customData&');
			categoryRequestString.push('query=ParentIDs|');
			categoryRequestString.push(categoryID);
			categoryRequestString.push('&');
			categoryRequestString.push('customField=backgroundImage&');
			categoryRequestString.push('customField=Keywords&');
			categoryRequestString.push('customField=IsDynamicPlaylist&');
			categoryRequestString.push('customField=GroupLevel&');
			categoryRequestString.push('customField=GroupOrder&');
			categoryRequestString.push('customField=Account&');
			categoryRequestString.push('customField=CreatedAfter&');
			categoryRequestString.push('customField=CreatedBefore&');
			categoryRequestString.push('customField=Genre&');
			categoryRequestString.push('customField=Show&');
			categoryRequestString.push('customField=SortField&');
			categoryRequestString.push('customField=MaxClips&');
			categoryRequestString.push('customField=SeasonNumber&');
			categoryRequestString.push('customField=Sport&');
			categoryRequestString.push('customField=Region&');
			categoryRequestString.push('customField=Event&');
			categoryRequestString.push('customField=People&');
			categoryRequestString.push('customField=CBCPersonalities&');
			categoryRequestString.push('customField=Aired&');
			categoryRequestString.push('customField=AudioVideo&');
			categoryRequestString.push('customField=BylineCredit&');
			categoryRequestString.push('customField=Characters&');
			categoryRequestString.push('customField=ClipType&');
			categoryRequestString.push('customField=EpisodeNumber&');
			categoryRequestString.push('customField=LiveOnDemand&');
			categoryRequestString.push('customField=Organizations&');
			categoryRequestString.push('customField=Producers&');
			categoryRequestString.push('customField=Segment&');
			categoryRequestString.push('customField=Sub-Event&');
			categoryRequestString.push('customField=SortOrder&');
			categoryRequestString.push('customField=AdCategory&');
			categoryResponse = function (response) {
				_this.displayLoading(false);
				_this.createCategoryObjects(response.items);
				if (response.context=="false") {
					_this.getNumberOfReleases(categoryID);
				}
			}
			var categoryRequest;
			if (isSideBar) {
				categoryRequest = new JSONRequest(categoryRequestString.join(''), "categoryResponse", "true");
			} else {
				categoryRequest = new JSONRequest(categoryRequestString.join(''), "categoryResponse", "false");
			}
			categoryRequest.send();
		},

		isEmpty: function (ob) {
			for (var i in ob) {
				return false;
			}
			return true;
		},

		pushToAllCategories: function (category) {
			if (this.isEmpty(this.findCategory(category.ID))) {
				allCategories.push(category);
			}
		},

		createCategoryObjects: function (response) {
			this.editBreadcrumbObject();
			var cat_tpl_data = [];
			for (var i = 0, length = response.length; i < length; i++) {
				thisCategory = new this.category(response[i]);
				thisCategory.GroupLevel = thisCategory.GroupLevel || 1;
				thisCategory.GroupOrder = thisCategory.GroupOrder || 1;
				cat_tpl_data.push({
					id: thisCategory.ID,
					link: thisCategory.hyperlink,
					label: thisCategory.title,
					group: thisCategory.GroupLevel,
					order: thisCategory.GroupOrder,
					logic: {
						isActive: false
					}
				});
				this.pushToAllCategories(thisCategory);
				cat_tpl_data.sort(this.categorySort);
				this.displayCategories(cat_tpl_data, _breadcrumbObject.length);
			}
			this.highlightElement(_breadcrumbObject[_breadcrumbObject.length - 1].ID, _previousCategory);
			_previousCategory = _breadcrumbObject[_breadcrumbObject.length - 1].ID;
			this.displayBreadcrumb(_breadcrumbObject);
			this.setURL();
		},

		editBreadcrumbObject: function () {
			var isThere = false;
			for (x in _breadcrumbObject) {
				if (_breadcrumbObject[x].ID == currentCategory.ID) {
					_breadcrumbObject.splice(x, _breadcrumbObject.length - x);
					isThere = true;
				}
			}
			for (x in _breadcrumbObject) {
				if (_breadcrumbObject[x].ID == currentCategory.parentID) {
					_breadcrumbObject.splice(parseInt(x) + 1, 1);
					isThere = true;
				}
			}
			_breadcrumbObject.push({
				link: "javascript:CBC.APP.UberPlayer.getCategoriesByID('" + currentCategory.ID + "');",
				label: currentCategory.title,
				ID: currentCategory.ID
			});
		},

		getNumberOfReleases: function (categoryID) {
			this.displayLoading(true);
			var releaseCount = [];
			releaseCount.push(_feedRoot);
			releaseCount.push('getReleaseList?');
			releaseCount.push('PID=');
			releaseCount.push(feedPID);
			releaseCount.push('&');
			if (currentCategory.IsDynamicPlaylist == "true") {
				if (currentCategory.Keywords) {
					releaseCount.push('query=KeywordsSearch|');
					for (x in currentCategory.Keywords.split(", ")) {
						releaseCount.push(currentCategory.Keywords.split(", ")[x]);
						releaseCount.push(',');
					}
					releaseCount.push('&');
				}
				if (currentCategory.Account != "(not specified)") {
					releaseCount.push('query=ContentCustomText|Account|');
					releaseCount.push(currentCategory.Account);
					releaseCount.push('&');
				}
				if (currentCategory.CreatedAfter) {
					releaseCount.push('query=ModifiedOnOrAfter|');
					releaseCount.push(currentCategory.CreatedAfter);
					releaseCount.push('&');
				}
				if (currentCategory.CreatedBefore) {
					releaseCount.push('query=ModifiedBefore|');
					releaseCount.push(currentCategory.CreatedBefore);
					releaseCount.push('&');
				}
				if (currentCategory.Genre != "Other") {
					releaseCount.push('query=ContentCustomText|Genre|');
					releaseCount.push(currentCategory.Genre);
					releaseCount.push('&');
				}
				if (currentCategory.Show != "(not specified)") {
					releaseCount.push('query=ContentCustomText|Show|');
					releaseCount.push(currentCategory.Show);
					releaseCount.push('&');
				}
				if (currentCategory.SeasonNumber) {
					releaseCount.push('query=ContentCustomText|SeasonNumber|');
					releaseCount.push(currentCategory.SeasonNumber);
					releaseCount.push('&');
				}
				if (currentCategory.Sport != "(not specified)") {
					releaseCount.push('query=ContentCustomText|Sport|');
					releaseCount.push(currentCategory.Sport);
					releaseCount.push('&');
				}
				if (currentCategory.Region != "(not specified)") {
					releaseCount.push('query=ContentCustomText|Region|');
					releaseCount.push(currentCategory.Region);
					releaseCount.push('&');
				}
				if (currentCategory.Event != "(not specified)" && currentCategory.Event != "") {
					releaseCount.push('query=ContentCustomText|Event|');
					releaseCount.push(currentCategory.Event);
					releaseCount.push('&');
				}
				if (currentCategory.People) {
					releaseCount.push('query=ContentCustomText|People|');
					releaseCount.push(currentCategory.People);
					releaseCount.push('&');
				}
				if (currentCategory.CBCPersonalities) {
					releaseCount.push('query=ContentCustomText|CBCPersonalities|');
					releaseCount.push(currentCategory.CBCPersonalities);
					releaseCount.push('&');
				}
				if (currentCategory.AudioVideo) {
					releaseCount.push('query=ContentCustomText|AudioVideo|');
					releaseCount.push(currentCategory.AudioVideo);
					releaseCount.push('&');
				}
				if (currentCategory.BylineCredit) {
					releaseCount.push('query=ContentCustomText|BylineCredit|');
					releaseCount.push(currentCategory.BylineCredit);
					releaseCount.push('&');
				}
				if (currentCategory.Characters) {
					releaseCount.push('query=ContentCustomText|Characters|');
					releaseCount.push(currentCategory.Characters);
					releaseCount.push('&');
				}
				if (currentCategory.ClipType != "(not specified)") {
					releaseCount.push('query=ContentCustomText|ClipType|');
					releaseCount.push(currentCategory.ClipType);
					releaseCount.push('&');
				}
				if (currentCategory.EpisodeNumber) {
					releaseCount.push('query=ContentCustomText|EpisodeNumber|');
					releaseCount.push(currentCategory.EpisodeNumber);
					releaseCount.push('&');
				}
				if (currentCategory.LiveOnDemand != "(not specified)") {
					releaseCount.push('query=ContentCustomText|LiveOnDemand|');
					releaseCount.push(currentCategory.LiveOnDemand);
					releaseCount.push('&');
				}
				if (currentCategory.Organizations) {
					releaseCount.push('query=ContentCustomText|Organizations|');
					releaseCount.push(currentCategory.Organizations);
					releaseCount.push('&');
				}
				if (currentCategory.Producers) {
					releaseCount.push('query=ContentCustomText|Producers|');
					releaseCount.push(currentCategory.Producers);
					releaseCount.push('&');
				}
				if (currentCategory.Segment) {
					releaseCount.push('query=ContentCustomText|Segment|');
					releaseCount.push(currentCategory.Segment);
					releaseCount.push('&');
				}
				if (currentCategory.SubEvent) {
					releaseCount.push('query=ContentCustomText|Sub-Event|');
					releaseCount.push(currentCategory.SubEvent);
					releaseCount.push('&');
				}
			} else {
				releaseCount.push('query=CategoryIDs|');
				releaseCount.push(categoryID);
				releaseCount.push('&');
			}
			var maxClips = (currentCategory.MaxClips) ? currentCategory.MaxClips : _pureMax;
			if (_currentSortField) {
				releaseCount.push('sortField=');
				releaseCount.push(_currentSortField);
				releaseCount.push('&');
				releaseCount.push('sortDescending=true&');
			} else if (currentCategory.SortField != "(not specified)") {
				releaseCount.push('sortField=');
				releaseCount.push(currentCategory.SortField);
				releaseCount.push('&');
				if (currentCategory.SortOrder=="Descending") {
					releaseCount.push('sortDescending=true&');
				}
			}
			releaseCount.push('endIndex=');
			releaseCount.push(maxClips);
			releaseCount.push('&');
			numOfReleasesResponse = function (response) {
				_this.displayLoading(false);
				if (response.items.length) {
					_this.createPaginationData(response, categoryID);
				}
			}
			var releaseCountRequest = new JSONRequest(releaseCount.join(''), "numOfReleasesResponse");
			releaseCountRequest.send();
		},

		getReleaseList: function (categoryID, currentPage) {
			this.displayLoading(true);
			var releaseRequestString = [];
			releaseRequestString.push(_feedRoot);
			releaseRequestString.push('getReleaseList?');
			releaseRequestString.push('PID=');
			releaseRequestString.push(feedPID);
			releaseRequestString.push('&');
			releaseRequestString.push('field=title&');
			releaseRequestString.push('field=PID&');
			releaseRequestString.push('field=ID&');
			releaseRequestString.push('field=description&');
			releaseRequestString.push('field=categoryIDs&');
			releaseRequestString.push('field=thumbnailURL&');
			releaseRequestString.push('field=URL&');
			releaseRequestString.push('field=added&');
			releaseRequestString.push('field=airdate&');
			releaseRequestString.push('field=expirationDate&');
			releaseRequestString.push('field=length&');
			releaseRequestString.push('field=Keywords&');
			releaseRequestString.push('contentCustomField=backgroundImage&');
			releaseRequestString.push('contentCustomField=show&');
			releaseRequestString.push('contentCustomField=relatedURL1&');
			releaseRequestString.push('contentCustomField=relatedURL2&');
			releaseRequestString.push('contentCustomField=relatedURL3&');
			releaseRequestString.push('contentCustomField=sport&');
			releaseRequestString.push('contentCustomField=seasonNumber&');
			releaseRequestString.push('contentCustomField=clipType&');
			releaseRequestString.push('contentCustomField=segment&');
			releaseRequestString.push('contentCustomField=event&');
			releaseRequestString.push('contentCustomField=adCategory&');
			releaseRequestString.push('contentCustomField=LiveOnDemand&');
			releaseRequestString.push('contentCustomField=AudioVideo&');
			releaseRequestString.push('contentCustomField=EpisodeNumber&');
			releaseRequestString.push('contentCustomField=RelatedClips&');
			releaseRequestString.push('contentCustomField=Genre&');
			releaseRequestString.push('contentCustomField=CommentsEnabled&');
			releaseRequestString.push('contentCustomField=CommentsExpirationDate&');
			if (currentCategory.IsDynamicPlaylist == "true") {
				if (currentCategory.Keywords) {
					releaseRequestString.push('query=KeywordsSearch|');
					for (x in currentCategory.Keywords.split(", ")) {
						releaseRequestString.push(currentCategory.Keywords.split(", ")[x]);
						releaseRequestString.push(',');
					}
					releaseRequestString.push('&');
				}
				if (currentCategory.Account != "(not specified)") {
					releaseRequestString.push('query=ContentCustomText|Account|');
					releaseRequestString.push(currentCategory.Account);
					releaseRequestString.push('&');
				}
				if (currentCategory.CreatedAfter) {
					releaseRequestString.push('query=ModifiedOnOrAfter|');
					releaseRequestString.push(currentCategory.CreatedAfter);
					releaseRequestString.push('&');
				}
				if (currentCategory.CreatedBefore) {
					releaseRequestString.push('query=ModifiedBefore|');
					releaseRequestString.push(currentCategory.CreatedBefore);
					releaseRequestString.push('&');
				}
				if (currentCategory.Genre != "Other") {
					releaseRequestString.push('query=ContentCustomText|Genre|');
					releaseRequestString.push(currentCategory.Genre);
					releaseRequestString.push('&');
				}
				if (currentCategory.Show != "(not specified)") {
					releaseRequestString.push('query=ContentCustomText|Show|');
					releaseRequestString.push(currentCategory.Show);
					releaseRequestString.push('&');
				}
				if (currentCategory.SeasonNumber) {
					releaseRequestString.push('query=ContentCustomText|SeasonNumber|');
					releaseRequestString.push(currentCategory.SeasonNumber);
					releaseRequestString.push('&');
				}
				if (currentCategory.Sport != "(not specified)") {
					releaseRequestString.push('query=ContentCustomText|Sport|');
					releaseRequestString.push(currentCategory.Sport);
					releaseRequestString.push('&');
				}
				if (currentCategory.Region != "(not specified)") {
					releaseRequestString.push('query=ContentCustomText|Region|');
					releaseRequestString.push(currentCategory.Region);
					releaseRequestString.push('&');
				}
				if (currentCategory.Event != "(not specified)" && currentCategory.Event != "") {
					releaseRequestString.push('query=ContentCustomText|Event|');
					releaseRequestString.push(currentCategory.Event);
					releaseRequestString.push('&');
				}
				if (currentCategory.People) {
					releaseRequestString.push('query=ContentCustomText|People|');
					releaseRequestString.push(currentCategory.People);
					releaseRequestString.push('&');
				}
				if (currentCategory.CBCPersonalities) {
					releaseRequestString.push('query=ContentCustomText|CBCPersonalities|');
					releaseRequestString.push(currentCategory.CBCPersonalities);
					releaseRequestString.push('&');
				}
				if (currentCategory.AudioVideo) {
					releaseRequestString.push('query=ContentCustomText|AudioVideo|');
					releaseRequestString.push(currentCategory.AudioVideo);
					releaseRequestString.push('&');
				}
				if (currentCategory.BylineCredit) {
					releaseRequestString.push('query=ContentCustomText|BylineCredit|');
					releaseRequestString.push(currentCategory.BylineCredit);
					releaseRequestString.push('&');
				}
				if (currentCategory.Characters) {
					releaseRequestString.push('query=ContentCustomText|Characters|');
					releaseRequestString.push(currentCategory.Characters);
					releaseRequestString.push('&');
				}
				if (currentCategory.ClipType != "(not specified)") {
					releaseRequestString.push('query=ContentCustomText|ClipType|');
					releaseRequestString.push(currentCategory.ClipType);
					releaseRequestString.push('&');
				}
				if (currentCategory.EpisodeNumber) {
					releaseRequestString.push('query=ContentCustomText|EpisodeNumber|');
					releaseRequestString.push(currentCategory.EpisodeNumber);
					releaseRequestString.push('&');
				}
				if (currentCategory.LiveOnDemand != "(not specified)") {
					releaseRequestString.push('query=ContentCustomText|LiveOnDemand|');
					releaseRequestString.push(currentCategory.LiveOnDemand);
					releaseRequestString.push('&');
				}
				if (currentCategory.Organizations) {
					releaseRequestString.push('query=ContentCustomText|Organizations|');
					releaseRequestString.push(currentCategory.Organizations);
					releaseRequestString.push('&');
				}
				if (currentCategory.Producers) {
					releaseRequestString.push('query=ContentCustomText|Producers|');
					releaseRequestString.push(currentCategory.Producers);
					releaseRequestString.push('&');
				}
				if (currentCategory.Segment) {
					releaseRequestString.push('query=ContentCustomText|Segment|');
					releaseRequestString.push(currentCategory.Segment);
					releaseRequestString.push('&');
				}
				if (currentCategory.SubEvent) {
					releaseRequestString.push('query=ContentCustomText|Sub-Event|');
					releaseRequestString.push(currentCategory.SubEvent);
					releaseRequestString.push('&');
				}
			} else {
				releaseRequestString.push('query=CategoryIDs|');
				releaseRequestString.push(categoryID);
				releaseRequestString.push('&');
			}
			var maxClips = (currentCategory.MaxClips) ? currentCategory.MaxClips : _pureMax;
			if (_currentSortField) {
				releaseRequestString.push('sortField=');
				releaseRequestString.push(_currentSortField);
				releaseRequestString.push('&');
				releaseRequestString.push('sortDescending=true&');
			} else if (currentCategory.SortField != "(not specified)") {
				releaseRequestString.push('sortField=');
				releaseRequestString.push(currentCategory.SortField);
				releaseRequestString.push('&');
				if (currentCategory.SortOrder=="Descending") {
					releaseRequestString.push('sortDescending=true&');
				}
			}
			page_data.currentPage = currentPage;
			releaseRequestString.push('startIndex=');
			releaseRequestString.push(parseInt((page_data.currentPage * page_data.pageMax) - (page_data.pageMax - 1)));
			releaseRequestString.push('&');
			releaseRequestString.push('endIndex=');
			if (maxClips < (page_data.currentPage * page_data.pageMax)) {
				releaseRequestString.push(parseInt(maxClips));
			} else {
				releaseRequestString.push(parseInt(page_data.currentPage * page_data.pageMax));
			}
			releaseRequestString.push('&');
			releasesResponse = function (response) {
				_this.displayLoading(false);
				if (response.items.length) {
					_this.createReleaseObjects(response.items, 'clips');
					_this.displayPagination(page_data);
				}
			}
			var releaseRequest = new JSONRequest(releaseRequestString.join(''), "releasesResponse");
			releaseRequest.send();
		},

		reOrder: function (targ, sortField) {
			this.switchFilter('libraryfilters',targ);
			this.getNumberOfReleases (currentCategory.ID);

		},

		createPaginationData: function (response, categoryID) {
			for (x in response.items) {
				if (response.items[x].ID == deepLinkRelease.ID) {
					if (x == 0) {
						deepLinkRelease.page = 1;
					} else {
						x++;
						deepLinkRelease.page = Math.ceil(x / page_data.pageMax);
					}
					break;
				}
			}
			var maxClips = (currentCategory.MaxClips) ? currentCategory.MaxClips : _pureMax;
			if (maxClips < response.items.length) {
				page_data.numOfReleases = maxClips;
			} else {
				page_data.numOfReleases = response.items.length;
			}
			page_data.totalPages = Math.ceil(page_data.numOfReleases / page_data.pageMax);
			page_data.currentPage = 1;
			if (deepLinkRelease.page == undefined) {
				this.getReleaseList(categoryID, 1);
			} else {
				this.getReleaseList(categoryID, deepLinkRelease.page);
			}
		},

		pushToAllReleases: function (release) {
			if (this.isEmpty(this.findRelease(release.ID))) {
				allReleases.push(release);
			}
		},

		createReleaseObjects: function (response, container) {
			var library_clip_data = [];
			for (var i = 0, length = response.length; i < length; i++) {
				thisRelease = new this.release(response[i]);
				library_clip_data.push({
					id: thisRelease.ID,
					rating: "35",
					ratings: "23",
					length: thisRelease.length,
					link: thisRelease.hyperlink,
					thumbnailURL: thisRelease.thumbnailURL,
					label: thisRelease.show,
					title: thisRelease.title,
					description: thisRelease.description,
					expiry: thisRelease.expirationDate,
					airdate: thisRelease.airdate,
					relatedClips: thisRelease.relatedClips,
					LiveOnDemand: thisRelease.liveOnDemand
				});
				this.pushToAllReleases(thisRelease);
				if (thisRelease.ID == deepLinkRelease.ID) {
					var deepLinkPlay = {url:thisRelease.URL,id:thisRelease.ID};
				}
				if (thisRelease.ID == currentRelease.ID) {
					var highlightClipID = thisRelease.ID;
				}
			}
			this.displayLibraryClips(library_clip_data, container);
			if (highlightClipID) {
				this.highlightElement(highlightClipID, null);
			}
			if (deepLinkPlay) {
				//deepLinkRelease.ID = 0;
				_this.playRelease(deepLinkPlay.url, deepLinkPlay.id);
				//deepLinkRelease = {};
			}
		},

		findCategory: function (categoryID) {
			var returnedCategory = {};
			for (x in allCategories) {
				if (allCategories[x].ID == categoryID) {
					returnedCategory = new this.category(allCategories[x]);
					break;
				}
			}
			return returnedCategory;
		},

		findRelease: function (releaseID) {
			var returnedRelease = {};
			for (x in allReleases) {
				if (allReleases[x].ID == releaseID) {
					returnedRelease = new this.release(allReleases[x]);
					break;
				}
			}
			return returnedRelease;
		},

		replaceSpaces: function (s) {
			return s && s.replace(/[ ]/g, "_");
		},

		replaceUnderscores: function (s) {
			return s && s.replace(/[_]/g, " ");
		},
		
		replaceAmpersands: function (s) {
			return s && s.replace(/[&]/g, "%26");
		},
		
		replaceQuestionMarks: function (s) {
			return s && s.replace(/[?]/g, "%3F");
		},
		
		replaceApostrophe: function (s) {
			return s && s.replace(/[']/g, "\\'");
		},

		setURL: function (ID) {
			if (ID) deepLinkRelease.ID = ID;
			var swfValue = [];
			for (x in _breadcrumbObject) {
				swfValue.push('/');
				swfValue.push(this.replaceSpaces(_breadcrumbObject[x].label));
			}
			if (deepLinkRelease.ID) {
				swfValue.push('/');
				swfValue.push('ID=');
				swfValue.push(deepLinkRelease.ID);
			} 
			SWFAddress.setValue(swfValue.join(''));
		},

		playRelease: function (URL, ID, overRide) {
			if (currentRelease.ID!=ID || overRide) {	
				this.switchMode("player");
				if (_adPlaying) {
					_releaseQueue.URL = URL;
					_releaseQueue.ID = ID;
				} else {
					_releaseQueue = {};
				}
				this.scrollPage("body");
				this.setURL(ID);
				this.highlightElement(ID, currentRelease.ID);
				var rel = this.findRelease(ID);
				this.setReleaseMetaData( rel );
				if (thisRelease.backgroundImage.length < 1) {
					_this.displaySponsorBg(currentSponsorImage);
				} else {
					_this.displaySponsorBg(thisRelease.backgroundImage);
				}
				currentRelease.ID = ID;
				tpController.setReleaseURL(URL, true);
				this.setRelated( rel );
				_previousRelease = ID;
				//mlwf
				//this.handleCommentsTabs(ID);
			}
		},

		setReleaseMetaData: function (thisRelease) {
			var meta_data = {};
			meta_data.title = thisRelease.title;
			meta_data.date = this.makeAirDate(thisRelease.airdate);
			meta_data.desc = thisRelease.description;
			meta_data.breadcrumb = [];
			var breadCrumbLink = '';
			for (x in _breadcrumbObject) {
				meta_data.breadcrumb[x] = {};
				meta_data.breadcrumb[x].label = _breadcrumbObject[x].label;
				breadCrumbLink += this.replaceApostrophe(_breadcrumbObject[x].label) + '/';
				meta_data.breadcrumb[x].link = "javascript:CBC.APP.UberPlayer.deepLink('" + breadCrumbLink + "');" + "CBC.APP.UberPlayer.scrollPage('library');";
			}
			meta_data.rlinks = [];
			if (thisRelease.relatedURL1) {
				meta_data.rlinks.push({
					link: thisRelease.relatedURL1.split("|")[1],
					label: thisRelease.relatedURL1.split("|")[0],
					target: "_blank"
				});
			}
			if (thisRelease.relatedURL2) {
				meta_data.rlinks.push({
					link: thisRelease.relatedURL2.split("|")[1],
					label: thisRelease.relatedURL2.split("|")[0],
					target: "_blank"
				});
			}
			if (thisRelease.relatedURL3) {
				meta_data.rlinks.push({
					link: thisRelease.relatedURL3.split("|")[1],
					label: thisRelease.relatedURL3.split("|")[0],
					target: "_blank"
				});
			}
			this.displayMetaData(meta_data);
		},

		setReleaseMetaDataFromRelated: function (title, airdate, description, relatedURL1, relatedURL2, relatedURL3) {
			var meta_data = {};
			meta_data.title = title;
			meta_data.date = this.makeAirDate(airdate);
			meta_data.desc = description;
			meta_data.breadcrumb = [];
			meta_data.rlinks = [];
			if (relatedURL1) {
				meta_data.rlinks.push({
					link: relatedURL1.split("|")[1],
					label: relatedURL1.split("|")[0],
					target: "_blank"
				});
			}
			if (relatedURL2) {
				meta_data.rlinks.push({
					link: relatedURL2.split("|")[1],
					label: relatedURL2.split("|")[0],
					target: "_blank"
				});
			}
			if (relatedURL3) {
				meta_data.rlinks.push({
					link: relatedURL3.split("|")[1],
					label: relatedURL3.split("|")[0],
					target: "_blank"
				});
			}
			this.displayMetaData(meta_data);
		},

		category: function (categoryInfo) {
			this.hyperlink = "javascript:CBC.APP.UberPlayer.getCategoriesByID('" + categoryInfo.ID + "');";
			this.title = categoryInfo.title;
			this.parentID = categoryInfo.parentID;
			this.ID = categoryInfo.ID;
			if (categoryInfo.customData) {
				for (x in categoryInfo.customData) {
					switch (categoryInfo.customData[x].title) {
						case "BackgroundImage":
							this.backgroundImage = categoryInfo.customData[x].value;
							break;
						case "Keywords":
							this.Keywords = categoryInfo.customData[x].value;
							break;
						case "IsDynamicPlaylist":
							this.IsDynamicPlaylist = categoryInfo.customData[x].value;
							break;
						case "GroupLevel":
							this.GroupLevel = categoryInfo.customData[x].value;
							break;
						case "GroupOrder":
							this.GroupOrder = categoryInfo.customData[x].value;
							break;
						case "Account":
							this.Account = categoryInfo.customData[x].value;
							break;
						case "CreatedAfter":
							this.CreatedAfter = categoryInfo.customData[x].value;
							break;
						case "CreatedBefore":
							this.CreatedBefore = categoryInfo.customData[x].value;
							break;
						case "Genre":
							this.Genre = categoryInfo.customData[x].value;
							break;
						case "Show":
							this.Show = categoryInfo.customData[x].value;
							break;
						case "SortField":
							this.SortField = categoryInfo.customData[x].value;
							break;
						case "MaxClips":
							this.MaxClips = categoryInfo.customData[x].value;
							break;
						case "SeasonNumber":
							this.SeasonNumber = categoryInfo.customData[x].value;
							break;
						case "Sport":
							this.Sport = categoryInfo.customData[x].value;
							break;
						case "Region":
							this.Region = categoryInfo.customData[x].value;
							break;
						case "Event":
							this.Event = categoryInfo.customData[x].value;
							break;
						case "People":
							this.People = categoryInfo.customData[x].value;
							break;
						case "CBCPersonalities":
							this.CBCPersonalities = categoryInfo.customData[x].value;
							break;
						case "Aired":
							this.Aired = categoryInfo.customData[x].value;
							break;
						case "AudioVideo":
							this.AudioVideo = categoryInfo.customData[x].value;
							break;
						case "BylineCredit":
							this.BylineCredit = categoryInfo.customData[x].value;
							break;
						case "Characters":
							this.Characters = categoryInfo.customData[x].value;
							break;
						case "ClipType":
							this.ClipType = categoryInfo.customData[x].value;
							break;
						case "EpisodeNumber":
							this.EpisodeNumber = categoryInfo.customData[x].value;
							break;
						case "LiveOnDemand":
							this.LiveOnDemand = categoryInfo.customData[x].value;
							break;
						case "Organizations":
							this.Organizations = categoryInfo.customData[x].value;
							break;
						case "Producers":
							this.Producers = categoryInfo.customData[x].value;
							break;
						case "Segment":
							this.Segment = categoryInfo.customData[x].value;
							break;
						case "Sub-Event":
							this.SubEvent = categoryInfo.customData[x].value;
							break;
						case "SortOrder":
							this.SortOrder = categoryInfo.customData[x].value;
							break;
						case "AdCategory":
							this.AdCategory = categoryInfo.customData[x].value;
							break;
					}
				}
			} else {
				this.backgroundImage = categoryInfo.backgroundImage;
				this.Keywords = categoryInfo.Keywords;
				this.IsDynamicPlaylist = categoryInfo.IsDynamicPlaylist;
				this.GroupLevel = categoryInfo.GroupLevel;
				this.GroupOrder = categoryInfo.GroupOrder;
				this.Account = categoryInfo.Account;
				this.CreatedAfter = categoryInfo.CreatedAfter;
				this.CreatedBefore = categoryInfo.CreatedBefore;
				this.Genre = categoryInfo.Genre;
				this.Show = categoryInfo.Show;
				this.SortField = categoryInfo.SortField;
				this.MaxClips = categoryInfo.MaxClips;
				this.SeasonNumber = categoryInfo.SeasonNumber;
				this.Sport = categoryInfo.Sport;
				this.Region = categoryInfo.Region;
				this.Event = categoryInfo.Event;
				this.People = categoryInfo.People;
				this.CBCPersonalities = categoryInfo.CBCPersonalities;
				this.Aired = categoryInfo.Aired;
				this.AudioVideo = categoryInfo.AudioVideo;
				this.BylineCredit = categoryInfo.BylineCredit;
				this.Characters = categoryInfo.Characters;
				this.ClipType = categoryInfo.ClipType;
				this.EpisodeNumber = categoryInfo.EpisodeNumber;
				this.LiveOnDemand = categoryInfo.LiveOnDemand;
				this.Organizations = categoryInfo.Organizations;
				this.Producers = categoryInfo.Producers;
				this.Segment = categoryInfo.Segment;
				this.SubEvent = categoryInfo.SubEvent;
				this.SortOrder = categoryInfo.SortOrder;
				this.AdCategory = categoryInfo.AdCategory;
			}
		},

		adParameters: function (release, adCategory) {
			var releaseURL = [];
			releaseURL.push(release.URL)
			releaseURL.push('&');
			var categoryCount = 0;
			for (x in release.categories) {
				var singleCagories = release.categories[x].split('/');
				for (y in singleCagories) {
					releaseURL.push('category');
					releaseURL.push(categoryCount);
					releaseURL.push('=');
					releaseURL.push(singleCagories[y]);
					releaseURL.push('&');
					categoryCount++;
				}
			}
			releaseURL.push('site=');
			if (_currentSection=="shows") {
				releaseURL.push('cbc.ent.ca');
			} else if (_currentSection=="news") {
				releaseURL.push('cbc.news.ca');
			} else if (_currentSection=="sports") {
				releaseURL.push('cbc.sports.ca');
			}
			releaseURL.push('&');
			var zone = "";
			if (adCategory) {
				zone += adCategory;
			} else if (currentCategory.AdCategory) {
				zone += currentCategory.AdCategory;
			} else {
				for (x in _breadcrumbObject) {
					zone += this.cleanAdParams(_breadcrumbObject[x].label);
				}
			}
			releaseURL.push('zone=');
			releaseURL.push(zone);
			releaseURL.push('&');
			if (release.length<120000) {
				releaseURL.push('shortClip=true&');
			} else {
				releaseURL.push('shortClip=false&');
			}
			if (release['contentCustomData']) {
				for (x in release['contentCustomData']) {
					switch (release['contentCustomData'][x].title) {
						case "Show":
							releaseURL.push('show=');
							releaseURL.push(this.cleanAdParams(release['contentCustomData'][x].value));
							releaseURL.push('&');
							break;
						case "Sport":
							releaseURL.push('sport=');
							releaseURL.push(this.cleanAdParams(release['contentCustomData'][x].value));
							releaseURL.push('&');
							break;
						case "SeasonNumber":
							releaseURL.push('season=');
							releaseURL.push(this.cleanAdParams(release['contentCustomData'][x].value));
							releaseURL.push('&');
							break;
						case "ClipType":
						releaseURL.push('type=');
							releaseURL.push(this.cleanAdParams(release['contentCustomData'][x].value));
							releaseURL.push('&');
							break;
						case "Segment":
							releaseURL.push('section=');
							releaseURL.push(this.cleanAdParams(release['contentCustomData'][x].value));
							releaseURL.push('&');
							break;
						case "Event":
							releaseURL.push('event=');
							releaseURL.push(this.cleanAdParams(release['contentCustomData'][x].value));
							releaseURL.push('&');
							break;
						case "LiveOnDemand":
							releaseURL.push('liveondemand=');
							releaseURL.push(this.cleanAdParams(release['contentCustomData'][x].value));
							releaseURL.push('&');
							break;
					}
				}
			} else {
				releaseURL.push('show=');
				releaseURL.push(this.cleanAdParams(release.show));
				releaseURL.push('&');
				releaseURL.push('sport=');
				releaseURL.push(this.cleanAdParams(release.sport));
				releaseURL.push('&');
				releaseURL.push('season=');
				releaseURL.push(this.cleanAdParams(release.seasonNumber));
				releaseURL.push('&');
				releaseURL.push('type=');
				releaseURL.push(this.cleanAdParams(release.clipType));
				releaseURL.push('&');
				releaseURL.push('section=');
				releaseURL.push(this.cleanAdParams(release.segment));
				releaseURL.push('&');
				releaseURL.push('event=');
				releaseURL.push(this.cleanAdParams(release.event));
				releaseURL.push('&');
				releaseURL.push('liveondemand=');
				releaseURL.push(this.cleanAdParams(release.liveOnDemand));
				releaseURL.push('&');
			}

			return releaseURL.join('');

		},

		release: function (releaseInfo) {
			this.breadCrumbObject = releaseInfo.breadCrumbObject;
			this.title = releaseInfo.title;
			this.categoryIDs = releaseInfo.categoryIDs;
			this.description = releaseInfo.description;
			this.thumbnailURL = releaseInfo.thumbnailURL;
			this.added = releaseInfo.added;
			this.keywords = releaseInfo.keywords;
			this.ID = releaseInfo.ID;
			this.airdate = releaseInfo.airdate;
			this.length = releaseInfo.length;
			this.expirationDate = _this.makeExpirationDate(releaseInfo.expirationDate);
			if (releaseInfo.contentCustomData) {
				for (x in releaseInfo.contentCustomData) {
					switch (releaseInfo.contentCustomData[x].title) {
						case "BackgroundImage":
							this.backgroundImage = releaseInfo.contentCustomData[x].value;
							break;
						case "Show":
							this.show = releaseInfo.contentCustomData[x].value;
							break;
						case "RelatedURL1":
							this.relatedURL1 = releaseInfo.contentCustomData[x].value;
							break;
						case "RelatedURL2":
							this.relatedURL2 = releaseInfo.contentCustomData[x].value;
							break;
						case "RelatedURL3":
							this.relatedURL3 = releaseInfo.contentCustomData[x].value;
							break;
						case "Sport":
							this.sport = releaseInfo.contentCustomData[x].value;
							break;
						case "SeasonNumber":
							this.seasonNumber = releaseInfo.contentCustomData[x].value;
							break;
						case "ClipType":
							this.clipType = releaseInfo.contentCustomData[x].value;
							break;
						case "Segment":
							this.segment = releaseInfo.contentCustomData[x].value;
							break;
						case "Event":
							this.event = releaseInfo.contentCustomData[x].value;
							break;
						case "AdCategory":
							this.adCategory = releaseInfo.contentCustomData[x].value;
							break;
						case "LiveOnDemand":
							this.liveOnDemand = releaseInfo.contentCustomData[x].value;
							break;
						case "AudioVideo":
							this.audioVideo = releaseInfo.contentCustomData[x].value;
							break;
						case "EpisodeNumber":
							this.episodeNumber = releaseInfo.contentCustomData[x].value;
							break;
						case "RelatedClips":
							this.relatedClips = releaseInfo.contentCustomData[x].value;
							break;
						case "Genre":
							this.genre = releaseInfo.contentCustomData[x].value;
							break;
						case "CommentsEnabled":
							this.commentsEnabled = releaseInfo.contentCustomData[x].value;
							break;
						case "ClipType":
							this.clipType = releaseInfo.contentCustomData[x].value;
							break;
					}
				}
				this.show = _this.makeShow(this);
				} else {
					this.backgroundImage = releaseInfo.backgroundImage;
					this.relatedURL1 = releaseInfo.relatedURL1;
					this.relatedURL2 = releaseInfo.relatedURL2;
					this.relatedURL3 = releaseInfo.relatedURL3;
					this.sport = releaseInfo.sport;
					this.seasonNumber = releaseInfo.seasonNumber;
					this.clipType = releaseInfo.clipType;
					this.segment = releaseInfo.segment;
					this.event = releaseInfo.event;
					this.adCategory = releaseInfo.adCategory;
					this.liveOnDemand = releaseInfo.liveOnDemand;
					this.audioVideo = releaseInfo.audioVideo;
					this.episodeNumber = releaseInfo.episodeNumber;
					this.relatedClips = releaseInfo.relatedClips;
					this.genre = releaseInfo.genre;
					this.clipType = releaseInfo.clipType;
					this.commentsEnabled = releaseInfo.commentsEnabled;
					this.show = releaseInfo.show;
					this.show = _this.makeShow(this);
			}
			this.URL = _this.adParameters(releaseInfo, this.adCategory);
			this.hyperlink = "javascript:CBC.APP.UberPlayer.playRelease('" + this.URL + "', '" + this.ID + "');";
		},

		makeShow: function (data) {
			if (data.show != "" && data.show != '(not specified)' && data.show != '(not applicable)' && data.show != undefined && data.show != null) {
				return data.show;
			} else if (data.event != "" && data.event != '(not specified)' && data.event != '(not applicable)' && data.event != undefined && data.event != null) {
				return data.event;
			} else if (data.sport != "" && data.sport != '(not specified)' && data.sport != '(not applicable)' && data.sport != undefined && data.sport != null) {
				return data.sport;
			} else if (data.genre != 'Other' && data.genre != undefined && data.genre != null) {
				return data.genre;
			} else {
				return data.audioVideo;
			}
		},

		makeExpirationDate: function (expirationDate) {
			var expirationDateHours = new Date(expirationDate).getTime();
			var todayHours = new Date().getTime();
			var newExpirationDate = (expirationDateHours - todayHours) / 3600000;
			return newExpirationDate;
		},

		removeSpaces: function (s) {
			return s && s.replace(/[ ]/g, "");
		},

		cleanAdParams: function (s) {
			return s && s.toLowerCase().replace(/[.,<>?\/;:"'{\[}\]|\\+=_-`!@#$%\^&*()]*|~*/g, "").replace(/[ ]/g, "_");
		},

		switchMode: function (mode) {
			if (mode != playerMode && playerMode != 'player') {
				switch (mode) {
					case "features":
						$D.addClass('feature', 'enabled');
						$D.removeClass('player', 'enabled');
						$D.removeClass('clipinfo', 'enabled');
						$D.addClass('ad', 'enabled');
						$D.removeClass('relatedplaylist', 'enabled');
						var newHeight = '270';
						showFeatures = true;
						break;
					case "player":
						$D.removeClass('feature', 'enabled');
						$D.addClass('player', 'enabled');
						$D.addClass('clipinfo', 'enabled');
						$D.addClass('ad', 'enabled');
						$D.addClass('relatedplaylist', 'enabled');
						showFeatures = false;
						var newHeight = '600';
						break;
				}
				// animation
				var anim = new YAHOO.util.Anim('maincontainer', { 'height': { from: parseInt($D.getStyle('maincontainer', 'height')), to: newHeight } }, 1, YAHOO.util.Easing.easeOut);
				anim.animate();
				playerMode = mode;
			}
		},

		switchLibraryTab: function (t, newTab) {
			$('library').className = t;
			_breadcrumbObject.length = 0;
		},

		switchFilter: function (container, el) {
			if (el.id=='fFeatured') {_currentSortField=null;}
			if (el.id=='fRecent') {_currentSortField="airdate";}
			if (el.id=='fWatched') {_currentSortField="requestCount";}
			var els = $D.getElementsByClassName('active', 'li', container);
			$D.removeClass(els, 'active');
			$D.addClass(el, 'active');
		},

		displayMetaData: function (data) {
			$('clipTitle').innerHTML = data.title;
			$('metaDateBreadcrumb').innerHTML = "<span>" + data.date + "</span>" + this.buildMetaBreadcrumb(data.breadcrumb);
			$('metaDesc').innerHTML = data.desc;
			$('rlinks').innerHTML = this.buildRelatedLinks(data.rlinks);
		},

		buildRelatedLinks: function (data) {
			var output = [];
			if (data.length > 0) {
				output.push('<h2>Related links:</h2>');
				output.push('<ul>');
				for (var i = 0; i < data.length; i++) {
					output.push('<li><a href="');
					output.push(data[i].link);
					output.push('" target="');
					output.push(data[i].target);
					output.push('"><span>&raquo;</span> ');
					output.push(data[i].label);
					output.push('</a></li>');
				}
				output.push('</ul>');
			}
			return output.join('');
		},

		buildMetaBreadcrumb: function (data) {
			var output = [];
			for (var i = 0; i < data.length; i++) {
				output.push('<a href="');
				output.push(data[i].link);
				output.push('">');
				output.push(data[i].label);
				output.push('</a>');
				if (i < data.length - 1) output.push(' &gt; ');
			}
			return output.join('');
		},

		categorySort: function (a, b) {
			var compare = function (x, y) {
				return x - y
			}
			return compare(a.group, b.group) || compare(a.order, b.order);
		},

		displayCategories: function (data, depth) {
			var output = "";
			var lastgroup = data[0].group;
			for (var i = 0; i < data.length; i++) {
				if (data[i].group != lastgroup) output += "<li></li>"; // inserts blank space between different groups
				lastgroup = data[i].group;
				output += $S.getVal('tpl_cat_item').evaluate(data[i]);
			}
			if (!depth) depth = 1;
			$('cats' + depth).innerHTML = output;
			// animation
			var newX = $D.getX('categories') + ($D.getX('catmask') - $D.getX('cats' + depth));
			var setAttr = function (a, v, u) {
				$D.setX('categories', v)
			};
			var anim = new YAHOO.util.Anim(null, {
				'scroll': {
					from: $D.getX('categories'),
					to: newX
				}
			},
			0.5, YAHOO.util.Easing.easeOut);
			anim.setAttribute = setAttr;
			anim.animate();
		},

		highlightElement: function (id, prevId) {
			if (id) id = id.toString();
			if (prevId) prevId = prevId.toString();
			if (prevId) $D.removeClass(prevId, 'active');
			if (id) $D.addClass(id, 'active');
		},

		displayLibraryClips: function(data, container) {
			var output = "";
			for (var i=0; i<data.length; i++) {
				var o = data[i];
				var _link = o.link;
				if (_link.indexOf("javascript:") == -1) {
					var _split = _link.split("/ID=");
					var _id = (_split.length > 1) ? _split[1] : "";
					if (!_searchObjects[_id]) _searchObjects[_id] = o;
					o.anchorAttrib = "onclick='CBC.APP.UberPlayer.playReleaseFromSearch(" + _id + ");return false;'";
				} else {
					o.anchorAttrib = "";
				}
				o.link = o.link.replace(/\/video\/watch\//ig,"/video/#/");
				trimLength = _maxDescLength;
				// Format expiry time to hours or days
				var e = o.expiry;
				if (e >= 24 && e <=_maxExpiryHrs) { // if expiry is between 1 and 7 days
					o.expiry = "Available for " + Math.round(e/24) + " more days";
				} else if (e > 0 && e < 24 ) { // if expiry is within 1 day
					o.expiry = "Available for " + Math.round(e) + " more hours";
				} else { // don't display expiry
					o.expiry = "";
					trimLength = _extendedDescLength; // create more space for description text
				}
				// Trim description if too long
				if (o.description.length > trimLength) {
					o.description = o.description.substr(0,trimLength) + "...";
				}
				// Format duration
				o.duration = this.msToHMS(o.length);
				// Use default thumb if necessary
				if (!o.thumbnailURL) o.thumbnailURL = _defaultThumbPath;
				// Add data required for live clips
				o.logic = {};
				if (o.LiveOnDemand == "Live") {
					var liveData = this.processLive(o.airdate);
					o.liveDate = liveData.date;
					o.liveTime = liveData.time;
					o.logic.liveState = liveData.state;
				} else {
					o.liveDate = '';
					o.liveTime = '';
					o.logic.liveState = "not";
					o.date = this.makeAirDate(o.airdate,true);
				}
				// Convert data into html
				output+= $S.getVal('tpl_library_clip').evaluate(o,o.logic);
			}
			$(container).innerHTML = output;
		},

		displayLoading: function (bool) {
			bool ? $D.addClass('loading', 'visible') : $D.removeClass('loading', 'visible');
		},

		displayBreadcrumb: function (data) {
			var output = "";
			if (data.length > 1) {
				for (var i = 0; i < data.length - 1; i++) {
					output += '<a href="' + data[i].link + '">' + data[i].label + '</a>';
				}
			}
			output += "<em>" + data[data.length - 1].label + "</em>";
			$('breadcrumb').innerHTML = output;
		},

		displaySponsorBg: function (path) {
			if (path) {
				var bg = 'url(' + path + ') no-repeat';
				$D.setStyle('maincontainer', 'background', bg);
			} else {
				var bg = 'url(' + defaultSponsorImage + ') no-repeat';
				$D.setStyle('maincontainer', 'background', bg);
			}
		},

		displayPagination: function(data) {
			var output = "";
			if (data.totalPages > 1) {
				if (data.currentPage > 1) {
					output += $S.getVal('tpl_page_step').evaluate({prevnext:'prev',label:'Previous',onclickfunc:data.onclickfunc,pg:data.currentPage-1});
				} else {
					output += $S.getVal('tpl_page_step_disabled').evaluate({prevnext:'prev',label:'Previous'});
				}
				var pages = data.totalPages;
				var page_start = data.currentPage-5;
				var page_end = data.currentPage+4;
				while (page_end > pages) { page_end--; page_start--; }
				while (page_start < 1) { page_start++; page_end++; }
				if (page_end > pages) page_end = pages;
				for (var i=page_start; i<=page_end; i++) {
					output += $S.getVal('tpl_page_num').evaluate({pg:i,onclickfunc:data.onclickfunc},{active:data.currentPage==i});
				}
				if (data.currentPage < data.totalPages) {
					output += $S.getVal('tpl_page_step').evaluate({prevnext:'next',label:'Next',onclickfunc:data.onclickfunc,pg:data.currentPage+1});
				} else {
					output += $S.getVal('tpl_page_step_disabled').evaluate({prevnext:'next',label:'Next'});
				}
			}
			$(data.container).innerHTML = output;
		},

		changePage: function (num) {
			// load new page of clips here
			page_data.currentPage = num;
			this.displayPagination(page_data);
			this.getReleaseList(currentCategory.ID, page_data.currentPage);
			return false;
		},

		scrollPage: function (id) {
			var setAttr = function (a, v, u) {
				window.scroll(0, v)
			};
			var anim = new YAHOO.util.Anim(null, {
				'scroll': {
					from: $D.getDocumentScrollTop(),
					to: $D.getXY(id)[1]
				}
			},
			0.5, YAHOO.util.Easing.easeOut);
			anim.setAttribute = setAttr;
			anim.animate();
		},

		getPlayerSwf: function ()
		{
			return swfobject.getObjectById("player");
		},

		setPlayerReleaseUrl: function ( url )
		{
			var swf = this.getPlayerSwf();
			if( swf )
			{
				if( swf.setReleaseUrl != null )
				{
					swf.setReleaseUrl( url );
				}
			}
		},

		setRelated: function ( release ) {
			var swf = swfobject.getObjectById("playlist");
			if ( swf ) {
				if (swf.setRelated != null) {
					swf.setRelated( release );
				}
			}
		},

		// SEARCH //
		getSearchResults: function(fieldId) {
			_searchQuery=$(fieldId).value;
			$('q-main').value = _searchQuery;
			$('q-top').value = _searchQuery;
			this.switchLibraryTab('search');
			if (fieldId == 'q-top') this.scrollPage('library');
			_searchStartIndex = 1;
			this.performSearch();
		},

		performSearch: function() {
			var qs="";
			qs+='q='+escape(_searchQuery);
			qs+='&start='+(_searchStartIndex-1);
			qs+='&num='+_searchResultsPerPage;
			qs+='&sort='+_searchFilter;
			this.displayLoading(true);
			$('searchclips').innerHTML = "";
			$('searchstatus').innerHTML = "Searching, please wait...";
			var callback = { success:this.performSearchResponse, failure: this.performSearchFail, scope: this, argument:{query:_searchQuery} };
			var req = YAHOO.util.Connect.asyncRequest('GET', _googleSearchBaseUrl+qs, callback);
			//$U.debug(_googleSearchBaseUrl+qs);
		},

		performSearchResponse: function(o) {
			this.displayLoading(false);
			$D.addClass('searchfilters', 'enabled');
			var numResults = 0;
			var totalPages = 0;
			var lastIndex = 0;
			var currentPage = 0;
			if (o.responseText) {
				var regex_node = new RegExp('&lt;(\/?.)&gt;','gm'); // convert entities to real characters
				o.responseText = o.responseText.replace(regex_node,'<$1>');
				o.responseText = o.responseText.replace(/&amp;/g,'&'); // convert ampersands
				//$U.debug(o.responseText);
				var data = eval('(' + o.responseText + ')').searchResults;
				_searchStartIndex = parseInt(data.firstIndex, 10);
				numResults = parseInt(data.numOfResults, 10);
				lastIndex = parseInt(data.lastIndex, 10);
				currentPage = Math.ceil(_searchStartIndex/_searchResultsPerPage);
				if (currentPage*_searchResultsPerPage > lastIndex) numResults = lastIndex;
					totalPages = Math.ceil(numResults/_searchResultsPerPage);
					if (data.items) {
						var newData = [];
						for (var i=0; i<data.items.length; i++) {
							var item = this.convertGoogleToPlatform(data.items[i]);
							newData.push(item);
						}
					}
				}
			if (numResults > 0) {
				$('searchstatus').innerHTML = "<strong>" + numResults + "</strong> items found matching '<strong>" + o.argument.query + "</strong>'.<br /><br />Displaying results <strong>"+_searchStartIndex+"-" + lastIndex + "</strong>:";
				this.createReleaseObjects(newData, 'searchclips');
				this.displayPagination({currentPage:currentPage,totalPages:totalPages,onclickfunc:'CBC.APP.UberPlayer.changeSearchPage',container:'searchpagination'});
			} else {
				$('searchstatus').innerHTML = "No items were found matching '<strong>" + o.argument.query + "'</strong>.<br /><br />Please modify your search query.";
			}
		},

		convertGoogleToPlatform: function(data) {
			var sectionIndex;
			if (data.url.indexOf('/Shows/')>0) {
				sectionIndex = data.url.indexOf('/Shows/');
				_currentSection='shows';
			}
			if (data.url.indexOf('/News/')>0) {
				sectionIndex = data.url.indexOf('/News/');
				_currentSection='news';
			}
			if (data.url.indexOf('/Sports/')>0) {
				sectionIndex = data.url.indexOf('/Sports/');
				_currentSection='sports';
			}
			var fullSectionString = data.url.substring(sectionIndex, data.url.indexOf('ID='));
			var ID = data.url.substring(data.url.indexOf('ID=')+3, data.url.length);
			if (fullSectionString.substring(0, 1)=='/') {
				fullSectionString = fullSectionString.substring(1, fullSectionString.length)
			}
			if (fullSectionString.substring(fullSectionString.length-1, fullSectionString.length)=='/') {
				fullSectionString = fullSectionString.substring(0, fullSectionString.length-1)
			}
			fullSectionString = fullSectionString.replace(/%20/g, ' ');
			var fullSectionStringSplit = fullSectionString.split('/');
			breadcrumbObject = [];
			for (var i in fullSectionStringSplit) {
				var bcObject = {};
				bcObject.ID = 0;
				bcObject.label = fullSectionStringSplit[i];	
				bcObject.link = "";
				breadcrumbObject.push(bcObject);
			}
			var newData = {};
			newData.breadCrumbObject = breadcrumbObject;
			newData.title = data.title;
			newData.description = data.metaData.description;
			newData.thumbnailURL = data.metaData.thumbnailURL;
			newData.ID = ID;
			newData.backgroundImage = "";
			newData.length = this.convertTimeToMS(data.metaData.runtime);
			newData.sport = data.metaData.Sport;
			newData.keywords = data.metaData.keywords;
			newData.airdate = data.metaData.airdate;
			newData.URL = data.metaData.playerURL;
			newData.show = data.metaData.Show;
			newData.liveOnDemand = data.metaData.LiveOnDemand;
			newData.audioVideo = data.metaData.AudioVideo;
			newData.genre = data.metaData.Genre;
			newData.URL = _this.adParameters(newData, newData.adCategory);
			newData.hyperlink = "javascript:CBC.APP.UberPlayer.playRelease('" + newData.URL + "', '" + newData.ID + "');";
			//NULLS:
			/*
			newData.categoryIDs = null;
			newData.added = null;
			newData.expirationDate = null;
			newData.relatedURL1 = null;
			newData.relatedURL2 = null;
			newData.relatedURL3 = null;
			newData.seasonNumber = null;
			newData.clipType = null;
			newData.segment = null;
			newData.event = null;
			newData.adCategory = null;
			newData.episodeNumber = null;
			newData.relatedClips = null;
			newData.clipType = null;
			newData.commentsEnabled = null;
			*/			
			return newData;
		},

		convertTimeToMS: function(time) {
			var newTime = 0;
			if (time) {
				var timeArray = time.split(':');
				for (x in timeArray) {
					if (x==0) {
						newTime += timeArray[0]*3600000;
					} else if (x==1) {
						newTime += timeArray[1]*60000;
					} else if (x==2) {
						newTime += timeArray[2]*1000;
					}
				}
			}
			return newTime;
		}, 

		performSearchFail: function(o) {
			// Didn't get search results
			this.displayLoading(false);
			$('searchstatus').innerHTML = "A problem occurred with the search. Please try your search query again.";
			//$U.debug('Search failed');
			//$U.debug(o);
		},
		
		changeSearchPage: function(num) {
			_searchStartIndex = ((num-1)*_searchResultsPerPage)+1;
			this.scrollPage('library');
			this.performSearch();
			return false;
		},
		
		changeSearchFilter: function(targ, filter) {
			this.switchFilter('searchfilters',targ);
			_searchFilter = filter;
		},

		// COMMENTS mlwf //
		handleCommentsTabs: function(clipId) {
			try {
				var _clip = this.findRelease(clipId);
				if (_clip.commentsEnabled == "Yes") {
					$S.setVal("cid","vid-"+clipId);
					$('ncomments').style.display = "inline";
					$S.setVal("scped",_clip.commentsExpirationDate);
					var article_type = _clip.audioVideo.toLowerCase();
					if (_clip.commentsExpirationDate) {
						$S.setVal("spMsg","Comments are [B]open[/B] and welcome until " + this.formatExpDate(_clip.CommentsExpirationDate) + ". We reserve the right to close comments before then.");
					} else {
						$S.setVal("spMsg","Comments are [B]open[/B]. We reserve the right to close comments at any time.");
					}
					$S.setVal("seMsg","This " + article_type + " is now closed to commenting.");
					$S.setVal("articleType",article_type);
					$S.setVal("cbcModule","storywrapper");
				}
			} catch(e) { $U.debug(e); }
		},

		//mlwf
		renderComments: function(_el) {
			try {
				var ctitle = currentCategory.title;
				switch (_currentSection)	{
					case "shows":
					$S.setVal("colourTheme","pgold");
					break;
					case "news":
					$S.setVal("colourTheme","pred");
					break;
					case "sports":
					$S.setVal("colourTheme","pblue");
					break;
					default:
					$S.setVal("colourTheme","pgold");
					break;
				}
				var _body = document.body;
				_body.className = _body.className.replace(/pred/ig,"").replace(/pblue/ig,"").replace(/pgold/ig,"");
				$D.addClass(_body, $S.getVal("colourTheme"));
				var _clip = this.findRelease(currentRelease.ID);
				CBC.APP.PLUCK.Comments.getData({_el:null,on_page:1,_title:_clip.title});
			} catch(e) { $U.debug(e); }
		},

		formatExpDate: function(timestamp) {
			try {
				var date = new Date(timestamp);
				var _month = "0"+(parseInt(date.getMonth())+1);
				_month = _month.substring(_month.length-2,_month.length);
				var _mins = "0"+date.getMinutes();
				_mins = _mins.substring(_mins.length-2,_mins.length);
				var _time = (date.getHours() < 12) ? ( ((date.getHours() == 0) ? 12 : date.getHours() )+":"+_mins+" AM ET") : ( (date.getHours() == 12) ? (date.getHours()): (date.getHours()-12) ) +":"+_mins+" PM ET";
				var _ts = $U.utc_days[date.getDay()] + ', ' + $U.utc_months[date.getMonth()] + ' ' + date.getDate() + ', ' + date.getFullYear()+ " at " + _time;
				return _ts;
			} catch(e) {
				$U.debug(e);
				return "";
			}
		},

		// TEMP FIXES //
		playReleaseFromSearch: function(_id) { //_o: metadata object
			this.scrollPage('body');
			this.switchMode("player");
			this.setRelated(_searchObjects[_id]);
			this.setReleaseMetaData(_searchObjects[_id]);
			tpController.setReleaseURL(_searchObjects[_id].playerURL, true);
			//this.setPlayerReleaseUrl();
		},

		// UTILITY //
		makeAirDate: function (date,isShort) {
			if (!date) return "";
			date = new Date(parseInt(date,10));
			var m = $U.utc_months[date.getMonth()];
			if (isShort) m = m.substr(0,3);
			return (m+" "+date.getDate()+", "+date.getFullYear());
		},

		msToHMS: function(ms) {
			if (!ms) return "";
			var h = Math.floor(ms/3600000);ms=ms%3600000;
			var m = Math.floor(ms/60000);ms=ms%60000;
			var s = ('0'+Math.floor(ms/1000));
			s = s.substr(s.length-2,s.length);
			var time = '';
			if (h>0) {
				time+=h+':';	
			}
			if ((m<10) && (h>0)) {
				time+='0'+m+':'+s;
			} else {
				time+=m+':'+s;
			}
			return time;
		},

		processLive: function (ae) {
			var airEpoch = parseInt(ae,10);
			var airDate = new Date(airEpoch);
			var todayDate = new Date();
			var todayEpoch = todayDate.getTime();
			var diff = airEpoch-todayEpoch;
			var tmrDate = new Date(todayEpoch);
			tmrDate.setDate(tmrDate.getDate()+1);
			if (todayDate.toDateString() == airDate.toDateString()) {
				var date = "Today";
			} else if (tmrDate.toDateString() == airDate.toDateString()) {
				var date = "Tomorrow";
			} else {
				var date = $U.utc_months[airDate.getMonth()].substr(0,3)+" "+airDate.getDate();
			}
			var state = diff>0 ? "later" : "now";
			return {date:date, time:this.formatTime(airDate), state:state};
		},

		formatTime: function(d) {
			if (!d) return "";
			var h = d.getHours();
			var ampm = h<12?" AM":" PM";
			if (h>12) h-= 12;
			else if (h==0) h = 12;
			var m = "0"+d.getMinutes();
			m = m.substr(m.length-2,2);
			return h+":"+m+ampm;
			}
		}
	}