if (window['errorlist'] === undefined) {
	window['errorlist'] = [];
}
window.onerror=function(m,f,l) {
	errorlist.push(f+" (line " + l + ") " + m);
	return true;
}

OneClipVideoListRenderer = {
	'OverrideOneClipImageUrl' : null,
	'OverrideOneClipImagePriority' : 0,
	'MaximumClipList' : 5,
	'PrerollFrequency':60,
	'AutoPlay':true,
	'DefaultPath' : 'Feature',
	'ThemePath' : 'http://watch.tsn.ca/themes/TSN/player/onecliptheme.aspx',
	'ErrorMessage':'',
	'arrOneClipVideoList' : {},
	'Redirects' : [],
	'UrlHash' : document.location.hash,
	'UrlPathname' : document.location.pathname,
	'ClipIdFromHash' : /clip(\d+)/,

	'TestRedirect' : function(strTest) {
		for (var i=0; i < OneClipVideoListRenderer.Redirects.length; i++) {
			var objRedirect = OneClipVideoListRenderer.Redirects[i];
			if (
				strTest.match(new RegExp(objRedirect.search)) 
				&& !OneClipVideoListRenderer.UrlPathname.match(new RegExp(objRedirect.url))
				&& !OneClipVideoListRenderer.UrlPathname.match(new RegExp('/(stories|fragment)/'))
				) {
				return objRedirect.url;
			}
		}
	},
	'OverrideOneClipImage' : function(strUrl,intPriority) {
		boolOverrideImage = true;
		if (OneClipVideoListRenderer.OverrideOneClipImagePriority != null && OneClipVideoListRenderer.OverrideOneClipImagePriority > intPriority) {
			boolOverrideImage = false;
		}
		if (boolOverrideImage) {
			OneClipVideoListRenderer.OverrideOneClipImageUrl = strUrl;
			OneClipVideoListRenderer.OverrideOneClipImagePriority = intPriority;
		}
	},
	'SetDefaultPath' : function(strPath) {
	    OneClipVideoListRenderer.DefaultPath = strPath == 'feature' ? 'featured' : strPath;
	},
	'AddClip' : function(objDetails) {
		if (OneClipVideoListRenderer.arrOneClipVideoList[OneClipVideoListRenderer.DefaultPath] === undefined) {
			OneClipVideoListRenderer.arrOneClipVideoList[OneClipVideoListRenderer.DefaultPath] = [];
		}
	    OneClipVideoListRenderer.arrOneClipVideoList[OneClipVideoListRenderer.DefaultPath].push(objDetails);
	},
	'ClearClips' : function() {
	    if (window["Playlist"]) {
//            Playlist.FeaturedVideos = new Array();
	    }
	    OneClipVideoListRenderer.arrOneClipVideoList[OneClipVideoListRenderer.DefaultPath] = new Array();
	},

	
	'RenderList' : function(fnRenderer) {
		if (OneClipVideoListRenderer.arrOneClipVideoList) {
			fnRenderer(OneClipVideoListRenderer.arrOneClipVideoList);
		}
	},
	'Bind' : function(fn,args) {
		return function() { fn(args) };
	},
	'LaunchPopupPlayer' : function(objDetails) {
	    Player.GetInstance().Wait();
		window.open('http://watch.tsn.ca/' + OneClipVideoListRenderer.DefaultPath + '/', 'TSNBroadband','width=1010,height=850,toolbar=0,status=0,scrollbars=1,resizable=1');
		return false;
	},
	'LoadOneClipPlayer' : function() {
        if (document.getElementById("tsnOneClipPlayer") && window["Interface"] && OneClipVideoListRenderer.arrOneClipVideoList[OneClipVideoListRenderer.DefaultPath] && OneClipVideoListRenderer.arrOneClipVideoList[OneClipVideoListRenderer.DefaultPath].length) {
			if (OneClipVideoListRenderer.OverrideOneClipImageUrl) {
				strTopImage = OneClipVideoListRenderer.OverrideOneClipImageUrl;
			}
			else {
				strTopImage = OneClipVideoListRenderer.arrOneClipVideoList[OneClipVideoListRenderer.DefaultPath][0].image + "/416/312/image.ashx";
			}

			if (window['Interface'] && Interface.DisplayPlayerControllerError) {
//					Interface.DisplayPlayerControllerError( "We're sorry", "There was an error loading your selection. Please try again or load the full player by clicking on the link below." );
				}
			try {
				Interface.PermalinkClicked = function( url ) {
					if( Playlist.GetInstance().Current.IsAd ) {window.open( url , "player" );}
					else {document.location = url;}
				}
			}
			catch(e) {
				OneClipVideoListRenderer.ErrorMessage += e.message;
			}
			
	        // Instantiate the player and create the playlist
			try {
				strAdpg = "/" + adpg;
			}
			catch(e) {
				strAdpg = "/main";
			}
	        Interface.GetInstance().PlayerViewer = document.getElementById("tsnOneClipPlayer");
            new Framework( Format.FlashVideo, OneClipVideoListRenderer.PrerollFrequency, "chumtvtsn", "One Clip Player", "ctv.tsnwatch.ca/nhlplayoffplayervideo ",OneClipVideoListRenderer.ThemePath, strTopImage);

	        // Loop through the videos in the list and push them into the player's playlist.
	        if (OneClipVideoListRenderer && OneClipVideoListRenderer.arrOneClipVideoList[OneClipVideoListRenderer.DefaultPath] && OneClipVideoListRenderer.arrOneClipVideoList[OneClipVideoListRenderer.DefaultPath].length) {
				Playlist.FeaturedVideos = new Array(); 
				var arrAutoPlayClipId = OneClipVideoListRenderer.UrlHash.match(OneClipVideoListRenderer.ClipIdFromHash);
				var intStartingVideoIndex = 0;
				var boolClipPlaying = false;
				
				if (arrAutoPlayClipId) {
					try {
						objAutoPlayClip = OneClipVideoListRenderer.FindDefaultPath(arrAutoPlayClipId[1]);
						if(objAutoPlayClip) {
							intStartingVideoIndex = objAutoPlayClip.clipindex;
							OneClipVideoListRenderer.DefaultPath = objAutoPlayClip.defaultpath;
						}
					} 
					catch(e) {}
				}
				
	            for (intOneClipVideo = intStartingVideoIndex; intOneClipVideo < OneClipVideoListRenderer.arrOneClipVideoList[OneClipVideoListRenderer.DefaultPath].length; intOneClipVideo++) {
		            objOneClipVideo = OneClipVideoListRenderer.arrOneClipVideoList[OneClipVideoListRenderer.DefaultPath][intOneClipVideo];
					if (objOneClipVideo['clipid']) {
						strTitle = objOneClipVideo['title'];
						intClipId = objOneClipVideo['clipid'];
						strFormat = objOneClipVideo['format'] ? objOneClipVideo['format'] : 'FLV';
						strUrl = objOneClipVideo['clippath'] ? objOneClipVideo['clippath'] : undefined;
						vidClip = new Video( {ClipId:intClipId, Title: strTitle, Format:strFormat, Url:strUrl});
						if (OneClipVideoListRenderer.AutoPlay && !boolClipPlaying) {
							Playlist.GetInstance().Play( vidClip );
							boolClipPlaying = true;
						}
						else {
							Playlist.FeaturedVideos.push( vidClip );
						}
					}
		            else if (objOneClipVideo['episodeclips']) {
						for (intEpisodeClip = 0; intEpisodeClip < objOneClipVideo['episodeclips'].length; intEpisodeClip++) {
							objEpisodeClip = objOneClipVideo['episodeclips'][intEpisodeClip];
							strTitle = objEpisodeClip['title'];
							intClipId = objEpisodeClip['clipid'];
							strFormat = objEpisodeClip['format'] ? objEpisodeClip['format'] : 'FLV';
	    		            vidClip = new Video( {ClipId:intClipId, Title: strTitle, Format:strFormat});
							if (OneClipVideoListRenderer.AutoPlay && !boolClipPlaying) {
								Playlist.GetInstance().Play( vidClip );
								boolClipPlaying = true;
							}
							else {
								Playlist.FeaturedVideos.push( vidClip );
							}
						}
		            }
				}
			}
        }
        return false;	
	},
	'FindDefaultPath':function(intClipId) {
		for (strDefaultPath in OneClipVideoListRenderer.arrOneClipVideoList) {
			if (OneClipVideoListRenderer.arrOneClipVideoList.hasOwnProperty(strDefaultPath)) {
				arrVideos = OneClipVideoListRenderer.arrOneClipVideoList[strDefaultPath];
				for (var i=0;i<arrVideos.length;i++) {
					objVideo = arrVideos[i];
					if (objVideo.clipid == intClipId) {
						return {'clipindex':i,'defaultpath':strDefaultPath};
					}
					else if (objVideo.episodeclips) {
						for (var j=0;j<objVideo.episodeclips.length;j++) {
							if (objVideo.episodeclips[j].clipid == intClipId) {
								return {'clipindex':i,'defaultpath':strDefaultPath};
							}
						}
					}
				}
			}
		}
		return false;
	},
	'PlayVideo' : function(intClip) {
		var bPlayClip = true;
		var _playlist = OneClipVideoListRenderer.arrOneClipVideoList[OneClipVideoListRenderer.DefaultPath];
		var vClip,intClipId,strFormat,strTitle,strUrl,objClip,objSegment;
	    Player.GetInstance().Wait();
		Playlist.FeaturedVideos = new Array();
		for (var i=intClip;i<_playlist.length;i++) {
			objClip=_playlist[i];
			if (objClip.episodeclips !== undefined) {
				for (var j=0;j<objClip.episodeclips.length;j++) {
					objSegment = objClip.episodeclips[j];
					intClipId=objSegment.clipid;
					strTitle = objSegment.title;
					strFormat=objSegment.format;
					vClip = new Video({ClipId:intClipId,Format:strFormat,Title:strTitle});
					if (bPlayClip) {
						Playlist.GetInstance().Play( vClip );
					}
					else {
						Playlist.FeaturedVideos.push( vClip );
					}
					bPlayClip = false;
				}
			}
			else {
				intClipId=objClip.clipid;
				strTitle = objClip.title;
				strFormat=objClip.format;
				vClip = new Video({ClipId:intClipId,Format:strFormat,Title:strTitle});
				if (bPlayClip) {
					Playlist.GetInstance().Play( vClip );
				}
				else {
					Playlist.FeaturedVideos.push( vClip );
				}
				bPlayClip = false;
			}
		}
		return true;
	}
};


window.onload = function() {
	// Public variables
	
	// Private variables
	var self = this;
	var arrTargets ={'nhl-long':document.getElementById('tsnOneClipVideoList1'),'nhl-games-on-demand':document.getElementById('tsnOneClipVideoList2')};
	var arrTabs = {'nhl-long':document.getElementById('tsnOneClipVideoListTrigger1'),'nhl-games-on-demand':document.getElementById('tsnOneClipVideoListTrigger2')};
	var strActiveTab = 'nhl-long';
	
	// Public methods
	this.renderer = function(arrClipLists) {
		var objClip;
		var intClipId;
		var arrClipList; // Note this is different from arrClipLists (plural)
		var strTitle,strDescription,strImage,strFormat;
		var objDescription,objImage,objAnchor,objH2,objDiv;
		for (var s in arrClipLists) {
			if (arrClipLists.hasOwnProperty(s)) {
				if (arrTargets[s]) {
					objTarget = arrTargets[s];
					arrClipList = arrClipLists[s];
					while(objTarget.childNodes.length) {
						objTarget.removeChild(objTarget.childNodes[0]);
					}
					for(var i=0; i<arrClipList.length;i++) {
						objClip = arrClipList[i];
						intClipId = objClip.clipid;
						strTitle = objClip.title;
						strDescription = objClip.description;
						strImage = objClip.image;
						strFormat = objClip.format;

						objDescription = _createElement('p',strDescription);
						objImage = _createElement('img',null,{'src':strImage + '/70/53/image.ashx','width':'70','height':'53','alt':''});
						objAnchor = _createElement('a',objImage,{'href':'#'});
						objAnchor.onclick = _bind(_triggerPlay,i);
						objH2 = _createElement('h2',strTitle);
						objAnchor2 = _createElement('a',objH2,{'href':'#'});
						objAnchor2.onclick = _bind(_triggerPlay,i);
						objDiv = _createElement('div',[objAnchor2,objAnchor,objDescription],{'class':'tsnOneClipClip'});
						objDiv.style.opacity='0.85';

						objTarget.appendChild(objDiv);
					}
				}
			}
		}


	}
	
	// Private methods
	var init = function() {
		_overrideOneClipCode();
		OneClipVideoListRenderer.ThemePath = 'http://images.tsn.ca/datafiles/xml/OneClip/TradeCentreTheme.xml';
		OneClipVideoListRenderer.ThemePath = 'http://watch.tsn.ca/themes/TSN/player/theme.aspx';
		OneClipVideoListRenderer.AutoPlay = true;
		OneClipVideoListRenderer.DefaultPath = strActiveTab;
		OneClipVideoListRenderer.LoadOneClipPlayer();
		OneClipVideoListRenderer.RenderList(self.renderer);
		_activateTabs();
		_showActiveTab();
	};
	var _overrideOneClipCode = function() {
		Interface.PermalinkClicked = function(url) {
			if( Playlist.GetInstance().Current.IsAd ) {window.open( url , "player" );}
		};
		Player.PermalinkClicked = function(url) {
			if( Playlist.GetInstance().Current.IsAd ) {window.open( url , "player" );}
		};

		Video.prototype.OnLoadFailure = function( pError ) {
			this.IsInErrorState = true;
			if( pError.match( "blocked" ) != null ) {
		        if( Interface.DisplayPlayerControllerError ) {
		            Interface.DisplayPlayerControllerError( "Not available in your region", "Sorry, the video you are trying to watch is <a href='http://blog.ctvdigital.net/index.php/video-player/video-player-faq/#OutsideCanada' target='_blank'>not available in your region</a>." );
		        }
		        else {
		            alert( "Canada only" );
		        }
		        Metrics.NavigatedTo( "Canada_Only" );
		    }
		    else if( pError.match( "expired" ) != null ) {
		        if( Interface.DisplayPlayerControllerError ) {
		            Interface.DisplayPlayerControllerError( "Clip expired", "The clip you are trying to watch is <a href='http://blog.ctvdigital.net/index.php/video-player/video-player-faq/#Expired' target='_blank'>no longer available</a>." );
		        }
		        else {
		            alert( "Clip expired" );
		        }
		         Metrics.NavigatedTo( "Clip_Expired" );
		    }
		    else {
			    if( Interface.DisplayPlayerControllerError ){
			        Interface.DisplayPlayerControllerError( "Sorry, there was an error", pError );
		        }
		        else {
		//            alert( "Sorry, there was an error" );
		        }
			}
			Metrics.ErrorPlayingClip( this, pError );
		};
			
	};
	var _activateTabs = function() {
		for (var strTab in arrTabs) {
			if (arrTabs.hasOwnProperty(strTab)) {
				arrTabs[strTab].onclick=_bind(_showActiveTab,strTab);
			}
		}
	};
	var _showActiveTab = function(s) {
		if (s) {
			strActiveTab = s;
		}
		for(var strTab in arrTargets) {
			if (arrTargets.hasOwnProperty(strTab)) {
				arrTargets[strTab].style.display = strTab === OneClipVideoListRenderer.DefaultPath ? 'block' : 'none';
				arrTabs[strTab].className = strTab === OneClipVideoListRenderer.DefaultPath ? 'tsnOneClipButton buttonOn' : 'tsnOneClipButton buttonOff';
			}
		}
		OneClipVideoListRenderer.DefaultPath = strActiveTab;
	};
	_triggerPlay = function(i) {
		OneClipVideoListRenderer.PlayVideo(i);
	};
	var _bind = function(fn,args) {
		return function(){fn(args)};
	};
	var _createElement = function(t,v,a){ // t = tagname, v = tag value, a = attribute list
		var objTag = document.createElement(t);
		if (v != undefined && v != null) {
			if (typeof(v) == 'string') {
				v = document.createTextNode(v);
				objTag.appendChild(v)
			}
			else if(v.length > 0) {
				for (var i=0;i<v.length;i++) {
					objTag.appendChild(v[i]);
				}
			}
			else {
				objTag.appendChild(v);
			}
		}
		if (a != undefined) {
			for (var s in a) {
				var n = document.createAttribute(s);
				n.value = a[s];
				objTag.setAttributeNode(n);
			}
		}
		return objTag;
	};
	init();
}