var Watch, Video, Player, CheckIds, Cookies, Links, PlayerButtons, Share, Styles, Truncate, VideoHovers, UpNext, WatchCookies, WatchSetup, WatchUtilities, WatchXML;

//if (jQuery.browser.msie && Video.browserVersion > 7) {

$(document).ready(function(){
	Video.init();
	Player.init();
	
	//	if (jQuery.browser.msie && Video.browserVersion > 7) {
	Watch.init();
	//	}
	
	$(window).resize(function(){
		Styles.posRight();
	});
	Watch.bLoad = false;
});
//}

/* MAIN METHODS: *WATCH* / VIDEO / PLAYER */

Watch = {
	//vars
	_strAjaxType: 'GET',
	_strVote: '10',
	bLoad: true,
	randomVideosTileNav: new VideoTileNavigation('whats-new'),
	UpNextClipsTileNav: new VideoTileNavigation('up-next-clips'),
	
	//methods
	init: function(){
	
WatchSetup.init();
		Cookies.init();
		Links.init();
		UpNext.init();
		VideoLinks.init();
		//		Disqus.init();
		Styles.init();
	}
};

/* MAIN METHODS: WATCH / *VIDEO* / PLAYER */
Video = {
	//vars
	_arrDuration: [],
	_arrSegIds: [],
	_cookie_bMuted: 'bMuted',
	_cookie_callUpNext: 'callUpNext',
	_cookie_collectionName: 'collectionName',
	_cookie_continuousEnabled: 'continuousEnabled',
	_cookie_deletedEpisodes: 'deletedEpisodes',
	_cookie_epCount: 'episodeCount',
	_cookie_upNextTab: 'upNextTab',
	_nDurationArrLen: 0,
	_nSegArrLen: 0,
	_nTotalPages: 1,
	_nVidChildren: 0,
	_objVidz: {
		_ncount: 0,
		_nPageCount: 0,
		_bbr: false
	},
	bCutItOut: false,
	bFirstrun: false,
	browserVersion: Number(jQuery.browser.version.split('.')[0]),
	bWatchPlayer: true,
	continuousEnabled: true,
	options: {
		path: '/'
	},
	regexChars: /[~`!@#\$\%\^\&*\(\)_\+=\{\}\[\]\|\\;\:\'\"<>,\.\?\/]/g,
	regexCollectionName: /(\/)([a-zA-Z0-9\-]+)(\/[a-zA-Z0-9\-]+?\.html)/,
	regexHyphens: /-/g,
	regexSpaces: / /g,
	regexTrailingHyphens: /-{1,}$/g,
	segIds: '',
	strCollectionName: '',
	
	// methods
	init: function(){
		try {
			switch (Video.strCollectionName) {
				case undefined:
				case 'undefined':
				case null:
				case '':
					Video.strCollectionName = location.pathname.replace(Video.regexCollectionName, '$2');
					break;
				default:
					break;
			}
		} 
		catch (e7a) {
			Video.strCollectionName = location.pathname.replace(Video.regexCollectionName, '$2');
		}
		try {
			switch ($.cookie(Video._cookie_continuousEnabled)) {
				case undefined:
				case 'undefined':
				case null:
				case '':
					Video.continuousEnabled = true;
					$.cookie(Video._cookie_continuousEnabled, Video.continuousEnabled, Video.options);
					break;
				default:
					break;
			}
		} 
		catch (e) {
			Video.continuousEnabled = true;
			$.cookie(Video._cookie_continuousEnabled, Video.continuousEnabled, Video.options);
		}
		if ($.cookie(Video._cookie_continuousEnabled) === 'true') {
			Video.continuousEnabled = true;
		}
		else {
			Video.continuousEnabled = false;
		}
	}
};

/* MAIN METHODS: WATCH / VIDEO / *PLAYER* */
Player = {
	//vars
	_nSeg: 0,
	attributes: {},
	bAutoRewind: false,
	bMute: '',
	bMutePressed: false,
	nMutePressedCount: true,
	bNext: '',
	bPause: false,
	bPlayEnded: false,
	bPrev: '',
	bUpNextFail: false,
	flashvars: {},
	intFlash: '',
	intPlayIt: '',
	objNowPlaying: null,
	oEvent: {},
	params: {},
	promoPlayerIds: {},
	sitePlayer: true,
	strName: '',
	strTitle: '',
	
	//methods
	init: function(){
		Player.flashvars = {
			configURL: Player.getConfigURL(),
			JSEventHandler: pageObj.JSEventHandler
		};
		
		Player.params = {
			allowscriptaccess: 'always',
			allownetworking: 'all',
			allowfullscreen: true,
			base: pageObj.playerBase,
			wmode: 'transparent'
		};
		
		Player.attributes = {
			id: pageObj.playerID,
			name: pageObj.playerID
		};
		
		var width = "670";
		var height = "377";
		
		// check if is a browse/landing/index page
		if (!Video.bWatchPlayer) {
			width = "260";
			height = "146";
		}
		
		var x;
		for (x in Player.flashvars) {
			if (x) {
			}
		}
		
		
		swfobject.embedSWF(pageObj.playerSource, "video-player", width, height, "9", false, {
			configURL: Player.getConfigURL(),
			JSEventHandler: pageObj.JSEventHandler
		}, Player.params, Player.attributes);
	},
	
	getConfigURL: function(){
		var URL = pageObj.configURL;
		var debugURL = swfobject.getQueryParamValue('configURL');
		
		if (debugURL.length && location.host.indexOf("adultswim.com") !== -1) {
			if (location.host !== "video.adultswim.com") {
				URL = debugURL;
			}
		}
		Utilities.debug('|-o-| URL ' + URL);
		
		return URL;
	},
	
	getTitle: function(strType){
		var t = null;
		var s = $('.adultswim-video-title').text();
		var a = s.split(':');
		switch (strType) {
			case 'collection':
				t = $('#adultswim-video-collection-title').text();
				break;
			case 'episode':
				t = $('#adultswim-video-episode-title').text();
				break;
			default:
				break;
		}
		return t;
	},
	
	getURI: function(){
		var u = window.location.href;
		return u;
	},
	
	
	nextEpisode: function(strName, strTitle){
		strName = Player.strName;
		strTitle = Player.strTitle;
		
		UpNext.singleton();
		
	},
	
	onPlayerEvent: function(p_event){
		Player.eventType = p_event.type;
		//Utilities.log('!! ' + p_event.type + ' : ' + Player.eventType);
		try {
			console.trace();
		} 
		catch (e) {
		}
		switch (p_event.type) {
			// player
			case 'playerInitSucceeded':
				pageObj.initialized = true;
				PlayerButtons.setMuteEnabled();
				if (jQuery.browser.msie && Video.browserVersion < 7) {
					Player.intPlayIt = setInterval(Player.playIt(), 1000);
				}
				else {
					Player.playIt();
				}
				Styles.posFF35Fix();
				break;
			case 'contentPlayEnded':
				Player.bPlayEnded = true;
				pageObj.initialized = true;
				if (jQuery.browser.msie && Video.browserVersion < 7) {
					Player.intPlayIt = setInterval(Player.playIt(), 1000);
				}
				else {
					Player.playIt();
				}
				break;
				
			//clicks
			case 'continuousPlaySet':
				Video.continuousEnabled = p_event.data;
				try {
					$.cookie(Video._cookie_continuousEnabled, Video.continuousEnabled, Video.options);
				} 
				catch (e) {
				}
				break;
			case 'nextClicked':
				Player.playIt('next');
				break;
			case 'previousClicked':
				Player.playIt('prev');
				break;
			case 'muteStateChanged':
			$.cookie(Video._cookie_bMuted, p_event.data, Video.options);
				break;
			//ads
			case 'adPlayStarted':
				Player.bNext = pageObj.nextEnabled;
				Player.bPrev = pageObj.prevEnabled;
				pageObj.nextEnabled = false;
				pageObj.prevEnabled = false;
				PlayerButtons.nextEnabled(pageObj.nextEnabled);
				PlayerButtons.setPrevEnabled(pageObj.prevEnabled);
				break;
			case 'adPlayEnded':
				pageObj.nextEnabled = Player.bNext;
				pageObj.prevEnabled = Player.bPrev;
				PlayerButtons.nextEnabled(pageObj.nextEnabled);
				PlayerButtons.setPrevEnabled(pageObj.prevEnabled);
				break;
				
			//failure
			case 'contentPlaylistFailed':
				swfobject.getObjectById(pageObj.playerID).showRelateds(true, 'Sorry. Looks like ' + Player.getTitle('episode') + ' is no longer available. You may like these instead. Or you may not.');
				break;
				
			// share buttons
			case 'commentsClicked':
				Player.bPause = true;
				Player.pauseVideo();
				$(window).scrollTop($("#comments").offset().top);
				break;
			case 'shareClicked':
				Share.shareSocial($('.share-this-video .email a'));
				break;
			case 'embedClicked':
				Share.shareSocial($('.share-this-video .embed a'));
				break;
			//default
			default:
				break;
		}
	},
	
	pauseVideo: function(){
	
		return (Player.bPause) ? swfobject.getObjectById(pageObj.playerID).pauseMedia() : swfobject.getObjectById(pageObj.playerID).playMedia();
	},
	
	playIt: function(str){
		Player.bPlayEnded = false;
		if (str === 'prev') {
			//iterate back twice -- once to compensate for this video and again to call up previous episode
			Player._nSeg--;
			Player._nSeg--;
		}
		try {
			clearInterval(Player.intPlayIt);
		} 
		catch (e) {
		}
		switch (Video._nSegArrLen) {
			case Player._nSeg:
				if (Player._nSeg > 0) {
					switch (str) {
						case 'prev':
							break;
						case 'next':
							if (Video.continuousEnabled) {
								Player.nextEpisode(null, null);
							}
							else {
								WatchUtilities.endCard();
							}
							break;
						default:
							if (Video.continuousEnabled) {
								Player.nextEpisode(null, null);
							}
							else {
								WatchUtilities.endCard();
							}
							break;
					}
				}
				break;
			default:
				if (Video.bWatchPlayer) {
					Player.playVideo({
						segmentIndex: Player._nSeg,
						segmentID: WatchUtilities.getSegId(Player._nSeg),
						episodeID: WatchUtilities.getVideoId(),
						customID: 'AS-' + WatchUtilities.getVideoId(),
						title: strPageName.replace(/&#039;/g, "'"),
						contentType: pageObj.episodeType,
						collectionTitle: strSubSectionName.replace(/&#039;/g, "'"),
						collectionID: WatchUtilities.getCollectionId(),
						videoPageURL: Player.getURI(),
						sectionID: pageObj.sectionID,
						duration: WatchUtilities.getDuration(Player._nSeg),
						rating: $('.adultswim-video-data .rating').text()
					});
				}
				else {
					try {
						if (Player.bUpNextFail) {
							Utilities.debug('|-o-| Player.bUpNextFail ' + Player.bUpNextFail);
							Player.bUpNextFail = false;
							Player._nSeg = 0;
							if (Utilities.getContentType() === 'CLI') {
								Video._nSegArrLen = 0;
							}
							else {
								Utilities.debug('|-oo-| nPlayer.bUpNextFail ' + Player.bUpNextFail);
								Video._nSegArrLen = Player.objNowPlaying.find('.thumbnail').attr('class').split(' ').length;
							}
							Utilities.debug('|-o-| segmentIndex: ' + Player._nSeg);
							Utilities.debug('|-o-| segmentID: ' + WatchUtilities.getSegId(Player._nSeg, Player.promoPlayerIds.segIdList));
							Utilities.debug('|-o-| episodeID: ' + $('.nowPlaying .thumbnail img').attr('class'));
						}
						if (Utilities.getContentType() === 'CLI') {
							Player._nSeg = 0;
							Video._nSegArrLen = 0;
						}
						Utilities.debug('|-o-| segmentIndex: ' + Player._nSeg);
						Utilities.debug('|-o-| segmentID: ' + WatchUtilities.getSegId(Player._nSeg, Player.promoPlayerIds.segIdList));
						Utilities.debug('|-o-| episodeID: ' + $('.nowPlaying .thumbnail img').attr('class'));
						Utilities.debug('|-o-| title: ' + $('.nowPlaying').find('.episode-title').text());
						Utilities.debug('|-o-| contentType: ' + Utilities.getContentType());
						Utilities.debug('|-o-| collectionTitle: ' + $('.nowPlaying').find('.episode-name').text());
						Utilities.debug('|-o-| collectionID: ' + WatchUtilities.getCollectionId());
						Utilities.debug('|-o-| videoPageURL: ' + Player.getURI());
						Utilities.debug('|-o-| sectionID: ' + pageObj.sectionID);
						Utilities.debug('|-o-| duration: ' + WatchUtilities.getDuration(Player._nSeg, $('.nowPlaying .duration').attr('class').replace('duration ', '')));
						Utilities.debug('|-o-| rating: ' + $('.nowPlaying').find('.rating').text());
						Utilities.debug('|-o-| success');
						Player.playVideo({
							segmentIndex: Player._nSeg,
							segmentID: WatchUtilities.getSegId(Player._nSeg, Player.promoPlayerIds.segIdList),
							episodeID: $('.nowPlaying .thumbnail img').attr('class'),
							customID: 'AS-' + WatchUtilities.getVideoId(),
							title: jQuery.trim($('.nowPlaying').find('.episode-title').text()),//Player.getTitle('episode'),
							contentType: Utilities.getContentType(),
							collectionTitle: jQuery.trim($('.nowPlaying').find('.episode-name').text()),//Player.getTitle('collection'),
							collectionID: WatchUtilities.getCollectionId(),
							videoPageURL: Player.getURI(),
							sectionID: pageObj.sectionID,
							duration: WatchUtilities.getDuration(Player._nSeg, $('.nowPlaying .duration').attr('class').replace('duration ', '')),
							rating: $('.nowPlaying').find('.rating').text()
						});
					} 
					catch (ePIb) {
						Player.bUpNextFail = true;
						Utilities.debug('|-o-| fail');
						Player._nSeg = 0;
						if (Utilities.getContentType() === 'CLI') {
							Video._nSegArrLen = 0;
						}
						else {
							Video._nSegArrLen = Player.objNowPlaying.find('.thumbnail').attr('class').split(' ').length;
						}
						Browse.itemCount = 0;
						Player.objNowPlaying = $('#listItem_' + Browse.itemCount);
						BrowseUtilities.init();
					}
				}
				if (Player._nSeg > 0) {
					pageObj.prevEnabled = true;
					PlayerButtons.setPrevEnabled(pageObj.prevEnabled);
				}
				else {
					pageObj.prevEnabled = false;
					PlayerButtons.setPrevEnabled(pageObj.prevEnabled);
				}
				Player._nSeg++;
				if ($('.all-my-episodes .are-belong-to-you li:first').attr('id') !== 'next-episode-z') {
					PlayerButtons.nextEnabled(pageObj.nextEnabled);
				}
				else {
					PlayerButtons.nextEnabled(false);
				}
				PlayerButtons.setContinuousEnabled();
				break;
		}
	},
	
	playVideo: function(p_context){
		var x;
		for (x in p_context) {
			if (x) {
			}
		}
		swfobject.getObjectById(pageObj.playerID).setMedia(p_context);
	},
	
	setPromoPlayerIds: function(videoId, segIdList){
		Player.promoPlayerIds.videoId = videoId;
		Player.promoPlayerIds.segIdList = segIdList;
	}
};

var CheckIds = {
	/* **** CHECK IDs **** */
	idOK: function(strID){
		var b;
		try {
			switch ($.cookie(Video._cookie_deletedEpisodes).match(strID)) {
				case null:
					switch (strID) {
						case WatchUtilities.getVideoId():
							Watch._bNowPlaying = true;
							b = false;
							break;
						default:
							b = true;
							break;
					}
					break;
				default:
					b = false;
					break;
			}
		} 
		catch (e) {
			switch (strID) {
				case WatchUtilities.getVideoId():
					Watch._bNowPlaying = true;
					b = false;
					break;
				default:
					b = true;
					break;
			}
		}
		return b;
	}
};

/**** COOKIE METHODS ****/
Cookies = {
	init: function(){
		// sniff collectionName cookie
		if ($.cookie(Video._cookie_collectionName) === Video.strCollectionName) {
			// if its the collection we're in...
			// set up Episode Counts
			Video._nEpisodeCount = parseInt($.cookie(Video._cookie_epCount), 10);
			////////////////////Utilities.log('0COOKIE ' + Video._nEpisodeCount + ' : ' + $.cookie(Video._cookie_epCount));
			Video._nUpNextCount = 0;
		}
		else {
			// else reset the cookies
			Cookies.setCookies();
		}
	},
	// delete cookies
	deleteCookies: function(){
		$.cookie(Video._cookie_epCount, null, Video.options);
		$.cookie(Video._cookie_collectionName, null, Video.options);
		$.cookie(Video._cookie_deletedEpisodes, null, Video.options);
		$.cookie(Video._cookie_upNextTab, null, Video.options);
	},
	// set/reset cookies
	setCookies: function(){
		Video.bFirstrun = true;
		$.cookie(Video._cookie_collectionName, Video.strCollectionName, Video.options);
		$.cookie(Video._cookie_epCount, 0, Video.options);
		if ($.cookie(Video._cookie_bMuted) === null) {
			$.cookie(Video._cookie_bMuted, false, Video.options);
		}
		Video._nEpisodeCount = parseInt($.cookie(Video._cookie_epCount), Video.options);
		Video._nUpNextCount = 0; // Video._nUpNextCount = Video._nEpisodeCount;
	}
};
Links = {
	//vars
	oNowShowing: {},
	strNowShowing: '',
	
	//methods
	init: function(){
		$('#adult-swim-video-nav-list > dt').hover(function(){
			$('.show-list-header-on').removeClass('show-list-header-on');
			$('#adult-swim-video-nav-list > dd').slideUp('medium', function(){
				Styles.removeClass('.show-list-on', 'show-list-on');
			});
			Links.strNowShowing = '#' + $(this).attr('id');
			$(this).addClass('show-list-header-on').nextUntil('dt').addClass('show-list-on').slideDown('medium');
		}, function(){
		});
		
		$('#adult-swim-video-nav-list').hover(function(){
		}, function(){
			$('.show-list-header-on').removeClass('show-list-header-on');
			$('#adult-swim-video-nav-list > dd').slideUp('medium', function(){
				Styles.removeClass('.show-list-on', 'show-list-on');
			});
		});
		
		VideoLinks.setupRollovers();
		$('#comments-and-rating .leave-a-comment a').click(function(){
			Player.bPause = true;
			Player.pauseVideo();
			$(window).scrollTop($("#comments").offset().top);
		});
		$('.share-this-video .email a').click(function(){
			Share.shareSocial($(this));
		});
		
		$('.share-this-video .facebook a').attr('target', '_blank').attr('href', 'http://www.facebook.com/share.php?u=' + window.location.href +
		'?cid=fb_share&amp;t=Watch ' +
		$('#adultswim-video-collection-title').text() +
		' - ' +
		$('#adultswim-video-episode-title').text() +
		' on adultswim.com"');
		
		$('.share-this-video .twitter a').attr('target', '_blank').attr('href', 'http://twitter.com/home?status=I\'m Watching ' +
		$('#adultswim-video-collection-title').text() +
		' - ' +
		$('#adultswim-video-episode-title').text() +
		' on adultswim.com:+' +
		window.location.href);
		$('.share-this-video .embed a').click(function(){
			Share.shareSocial($(this));
		});
		$('#electoral-college a').click(function(){
			Watch._bGetOutTheVote = true;
			Watch._strVote = $(this).text();
			
			$.ajax({
				type: 'POST',
				url: '/adultswimdynamic/asfix-svc/services/postRating?id=' + WatchUtilities.getVideoId() + '&rating=' + Watch._strVote + '&networkName=AS',
				dataType: 'xml',
				success: function(xml){
				},
				error: function(XMLHttpRequest, textStatus, errorThrown){
				},
				complete: function(xml){
					Watch._strAjaxType = 'GET';
					Watch._bGetOutTheVote = false;
				}
			})
			
			$('#electoral-college .on').removeClass('on');
			$(this).parent().addClass('on');
		});
		
	},
	truncate_link: function(){
		var boxHeight = $('#adultswim-video-details').height();
		$('.more_link').click(function(){
			var textContainer = $(this).parent().children('.text-container');
			
			$('#adultswim-video-episode-title, .adultswim-video-episode-details').toggle();
			if ($(this).html().match('More')) {
				textContainer.html($(this).parent().attr('data-full-text') + ' ');
				/*Utilities.log(boxHeight 
					+ ' :: ' 
					+ $(this).parent().children('.text-container').outerHeight() 
					+ ' : ' +
					+ $(this).parent().children('.text-container').children().outerHeight() 
					+ ' : ' +
					+ $(this).parent().children('.text-container span').outerHeight());*/
				
				if (boxHeight <= $(this).parent().children('.text-container').outerHeight()) {
					//console.log('true')
					$('#adultswim-video-details').css({
						'height': (boxHeight + 30),
						'margin-top': '-30px'
					});
				}
				$(this).html($(this).html().replace(/More/, 'Less'));
				$(this).closest('div').css({
					'margin-top': '0'
				});
			}
			else {
				textContainer.html($(this).parent().attr('data-trunc-text') + '... ');
				$('#adultswim-video-details').css({
					'height': boxHeight,
					'margin-top': '0px'
				});
				$(this).html($(this).html().replace(/Less/, 'More'));
				$(this).closest('div').css({
					'margin-top': '10px'
				});
			}
		});
	}
};

PlayerButtons = {
	nextEnabled: function(nextEnabled){
		swfobject.getObjectById(pageObj.playerID).setNextEnabled(nextEnabled);
	},
	
	setContinuousEnabled: function(){
		try {
			swfobject.getObjectById(pageObj.playerID).setContinuousPlaySelected(Video.continuousEnabled);
		} 
		catch (eSCE) {
		}
	},
	
	setMuteEnabled: function(){
		Player.bMute = $.cookie(Video._cookie_bMuted) === 'true' ? true : false;
		try {
			swfobject.getObjectById(pageObj.playerID).setMuted(Player.bMute);
		} 
		catch (eSME) {
		}
	},
	
	setPrevEnabled: function(prevEnabled){
		swfobject.getObjectById(pageObj.playerID).setPreviousEnabled(prevEnabled);
	}
};

var Share = {
	clip: new ZeroClipboard.Client(),
	init: function(){
		$('.email-form-div .mailer').each(function(){
			$(this).focus(function(){
				$('.email-form-div .mailer').each(function(){
					$(this).removeClass('mailer-on');
				});
				$(this).addClass('mailer-on');
			}).blur(function(){
				$(this).removeClass('mailer-on');
			});
		})
		/* **** email submit binder **** */
		$('.overlay-share-span-right').bind("submit", function(event){
			Share.mailSent();
			Share.clearFields();
			return false;
		});
	},
	/* *** EMAIL STUFF *** */
	clearFields: function(){
		$('.overlay-share-span-right').find('.mailer').each(function(i){
			$(this).val('').removeClass('on').parents('.required').removeClass('required');
		});
		$('.emailMsg textarea').val(Watch.strEmailMsg);
	},
	fader: function(){
		$('#messageSent').fadeOut(1500, function(){
			$('#messageSent').remove();
			$('#emailiframe').remove();
			$('.email-adultswim-video-send').unbind('mousemove', Share.fader);
		});
	},
	mailSent: function(){
		$('#share-overlay-div').append('<div id="messageSent"></div>');
		
		$('#messageSent').hide().append('<p>Your Message Has Been Sent!</p>').fadeIn(300, function(){
			$('.overlay-share-span-right').bind('mousemove', Share.fader);
		})
	},
	shareSocial: function(elem){
		Player.bPause = true;
		Player.pauseVideo();
		WatchUtilities.videoOverlay();
		
		$('#share-overlay').append('<div id="share-overlay-div"></div>')
		$('#share-overlay-div').append('<span class="overlay-share-span-left"></span>').append('<span class="overlay-share-span-right"></span>');
		
		var strCopyButton = 'Copy Code';
		
		switch ($(elem).parent().attr('class')) {
			case 'embed':
				$('#share-overlay-div').addClass('embed');
				$('.overlay-share-span-left').append('<strong>Embed</strong>').append('<img src="' +
				$('meta[property="og:image"]').attr('content') +
				'" class="overlay-embed-image" alt="' +
				$('#adultswim-video-episode-title').text() +
				' - ' +
				$('#adultswim-video-collection-title').text() +
				'" />').append('<div class="overlay-share-span-left-inner-div"></div>').css({
					'border-right': 'none'
				});
				
				$('.overlay-share-span-left-inner-div').append('<strong>Code:</strong>').append('<textarea class="textarea embed-code">' +
				'<object type="application/x-shockwave-flash" width="425" height="350" data="http://i.adultswim.com/adultswim/video3/tools/swf/viralplayer.swf">' +
				'<param name="allowFullScreen" value="true" />' +
				'<param name="movie" value="http://i.adultswim.com/adultswim/video3/tools/swf/viralplayer.swf"/>' +
				'<param name="FlashVars" value="id=' +
				$('#adultswim-video-details').attr('data-episode-id') +
				'" />' +
				'<embed src="http://i.adultswim.com/adultswim/video3/tools/swf/viralplayer.swf" type="application/x-shockwave-flash" FlashVars="id=' +
				$('#adultswim-video-details').attr('data-episode-id') +
				'" allowFullScreen="true" width="425" height="350"></embed>' +
				'</object>' +
				'</textarea>');
				break;
			default:
				
				strCopyButton = 'Copy Link';
				
				$('#share-overlay-div').addClass('social');
				
				$('.overlay-share-span-left').append('<p>Post to one of these sites:</p>').append('<ul class="share-sites">').append('<span class="share-overlay-permalink"></span>');
				
				$('ul.share-sites').append('<li class="facebook"><a href="http://www.facebook.com/share.php?u=' + window.location.href +
				'?cid=fb_share&amp;t=Watch ' +
				$('#adultswim-video-collection-title').text() +
				' - ' +
				$('#adultswim-video-episode-title').text() +
				' on adultswim.com" target="_blank" title="Post ' +
				$('#adultswim-video-episode-title').text() +
				' to Facebook">' +
				'<img src="../tools/img/share-fb.png" alt="Share on facebook" />' +
				'<strong>Facebook</strong>' +
				'</a></li>').append('<li class="twitter"><a href="http://twitter.com/home?status=I\'m Watching ' +
				$('#adultswim-video-collection-title').text() +
				' - ' +
				$('#adultswim-video-episode-title').text() +
				' on adultswim.com:+' +
				window.location.href +
				'" target="_blank" title="Twitter this page">' +
				'<img src="../tools/img/share-tw.png" alt="Share on twitter" />' +
				'<strong>Twitter</strong>' +
				'</a></li>');
				
				$('#share-overlay .share-overlay-permalink').append('<p>Permalink:</p>').append('<input class="permalink textarea" value="' + window.location + '" />');
				
				$('.overlay-share-span-right').append('<form class="email-form"></form>').append('<div class="emailButtons"></div>');
				
				$('.email-form').append('<input type="hidden" class="hidden videosubject" name="VIDEO_SUBJECT" value="Watch ' +
				$('#adultswim-video-collection-title').text() +
				' - ' +
				$('#adultswim-video-episode-title').text() +
				' on adultswim.com" />').append('<input type="hidden" class="hidden videouri" name="VIDEO_URI" value="&lt;a href=&quot;' +
				window.location.href +
				'&quot;&gt;Watch ' +
				$('#adultswim-video-collection-title').text() +
				' - ' +
				$('#adultswim-video-episode-title').text() +
				' on adultswim.com&lt;/a&gt;">').append('<div class="email-form-div left"></div>');
				
				$('.email-form-div').append('<div class="emYName">' +
				'<label>You:</label>' +
				'<input type="text" value="" name="name" class="mailer" />' +
				'</div>').append('<div class="emYEmail">' +
				'<label>Email:</label>' +
				'<input type="text" value="" name="email" class="mailer email">' +
				'</div>').append('<div class="emFName">' +
				'<label>Friend:</label>' +
				'<input type="text" value="" name="friend" class="mailer">' +
				'</div>').append('<div class="emFEmail">' +
				'<label>Email:</label>' +
				'<input type="text" value="" name="friendemail" class="mailer email">' +
				'</div>').append('<div class="emailMsg"></div>');
				
				$('.emailMsg').append('<h4>Message:</h4>').append('<span class="message-text">Hey! Your friend thinks you should watch ' + $('#adultswim-video-collection-title').text() + '&apos;s ' + $('#adultswim-video-episode-title').text() + ' from adultswim.com. We think you should find a new friend.</span>');
				
				$('.emailButtons').append('<div class="email-adultswim-video-send"><a class="copier" href="javascript:Share.submitForm();"><span>SEND</span></a></div>');
				
				Share.init();
				
				
				break;
		}
		$('.overlay-share-span-left').append('<a href="javascript:void(0);" class="copier"><span>' + strCopyButton + '</span></a>');
		
		$('#share-overlay-div').css({
			'height': $('.overlay-share-span-left').outerHeight(),
			'margin': '0 0 0 18px ',
			'margin-top': parseInt(($('#pod6 object').outerHeight() - $('.overlay-share-span-left').outerHeight()) / 2),
			'width': $('#pod6').width()
		});
		Share.clip.glue($('#share-overlay a.copier:first'), escape($('#share-overlay-div').find('.textarea:first').val()));
		
		//Grab the text from the parent row of the icon
		Share.clip.setText(escape($('#share-overlay-div .textarea:first').val()));
		
		$('.copier:eq(1)').css({
			'margin-top': parseInt($('.copier:eq(0)').position().top - $('.copier:eq(1)').position().top + 5)
		});
		$('#copier-swf-holder-holder').hover(function(){
			$('a.copier:first').css({
				'background': '#f73e9f'
			});
		}, function(){
			$('a.copier:first').css({
				'background': '#4492b9'
			});
		});
	},
	submitForm: function(){
		var bMoveAlong = true;
		$('.overlay-share-span-right .email-form').find('.mailer').each(function(i){
			($(this).val() == '' && !$(this).is('textarea')) ? $(this).parent().addClass('required') : $(this).parent().removeClass('required');
			
			if ($(this).hasClass('email')) {
				var test = /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test($(this).val());
				(test == false) ? $(this).parent().addClass('required') : $(this).parent().removeClass('required');
			}
		});
		$('.overlay-share-span-right .email-form').find(".required").filter(function(index){
			bMoveAlong = false;
		});
		if (bMoveAlong) {
			$('#footer-container').append('<iframe id="emailiframe" />');

			$('#emailiframe').width(1).height(1).attr('src', 'http://poll.turner.com/ViewsFlash/servlet/viewsflash?VIDEO_SUBJECT=' +
			$('.overlay-share-span-right .email-form .videosubject').val() +
			'&VIDEO_URI=' +
			$('.overlay-share-span-right .email-form .videouri').val() +
			'&YOUR_NAME=' +
			$('.emYName').find('input').val() +
			'&YOUR_EMAIL=' +
			$('.emYEmail').find('input').val() +
			'&FRIENDS_NAME=' +
			$('.emFName').find('input').val() +
			'&FRIENDS_EMAIL=' +
			$('.emFEmail').find('input').val() +
			'&MESSAGE=' +
			$('.emailMsg .message-text').text() +
			'&submitsubmit=Submit&cmd=tally&pollid=AdultSwim%21as_video_email&vwf_showquestion=&results=AdultSwim%21as_video_email.results.html&pagenumber=0&charset=UTF-8&vwf_ShowAndHide_HiddenQuestions=');
			
			$('.overlay-share-span-right .email-form').trigger("submit");
		}
	}
}
Styles = {
	//vars
	arrSect: [],
	arrUNHeight: [],
	
	//methods
	init: function(){
		Styles.posRight();
		
		var nCarTop = $('#comments-and-rating').position().top;
		try {
			var nVidPosBot = $('#adultswimVideoPlayer').position().top +
			$('#adultswimVideoPlayer').outerHeight();
		} 
		catch (eSi) {
		}
		
		//Styles.posComments();
		Truncate.init();
		if (!jQuery.browser.msie) {
			$('.facebook-like').css({
				'margin-top': '-27px',
				'left': parseInt($('#electoral-college').position().left + $('#electoral-college').width() + 15) + 'px'
			});
		}
		else {
			if (Video.browserVersion > 7) {
			$('.facebook-like').css({
				'margin-top': '0px',
				'left': parseInt($('#electoral-college').position().left + $('#electoral-college').width() + 15) + 'px'
			});
			}
		}
		if (!jQuery.support.checkOn) { // chrome
			$('.facebook-like').css({
				'margin-top': '-7px'
			});
			$('#comments-and-rating .leave-a-comment').css({
				'height': '31px',
				'line-height': '20px'
			});
			$('#comments-and-rating .share-this-video').css({
				'height': '28px',
				'line-height': '20px'
			});
			$('#comments-and-rating .electoral-college-span').css({
				'height': '26px',
				'line-height': '20px'
			});
		}
		else {
			if (jQuery.browser.msie){
				if (Video.browserVersion < 8) {
					$('.facebook-like').css({
						'margin-top': '-7px'
					});
				}
				else if (Video.browserVersion == 8) {
					$('.facebook-like').css({
						'margin-top': '-7px'
					});
				}
				else {
					$('.facebook-like').css({
						'margin-top': '-7px'
					});
				}
			}
		}
	},
	// fix for ff 3.5 positioning error (up-next-featured, up-next-filters, #up-next .up-next)
	posFF35Fix: function(){
		if (jQuery.browser.mozilla) {
			if (jQuery.browser.version.localeCompare('1.9.2') == -1) {
			
				var o1a = $('#up-next-episodes').offset();
				var o2a = $('#up-next-featured').offset();
				var dxa = o1a.left - o2a.left;
				var dya = o1a.top - o2a.top;
				var dista = Math.sqrt(dxa * dxa + dya * dya);
				
				var o1b = $('#up-next-clips').offset();
				var o2b = $('#up-next-featured').offset();
				var dxb = o1b.left - o2b.left;
				var dyb = o1b.top - o2b.top;
				var distb = Math.sqrt(dxb * dxb + dyb * dyb);
				
				var topOfDiv = $('#up-next-featured').offset().top;
				var bottomOfVisibleWindow = $(window).height();
				
				$('#up-next-featured').css({
					'margin-top': '-91px'
				});
			}
		}
	},
	posRight: function(){
		WatchUtilities.videoOverlayStyles();
		$('.up-next-filters').css({
			'right': $('.up-next-filters').closest('article').find('section').position().left +
			20
		});
		Styles.posFF35Fix();
		try {
			$('.more-videos-filters').css({
				'right': $('.more-videos-filters').closest('article').find('section').position().left +
				20
			});
			
		} 
		catch (e) {
		
		}
		$('.facebook-like').css({
			'left': parseInt($('#electoral-college').position().left + $('#electoral-college').width() + 15) + 'px'
		});
	},
	removeClass: function(e, strClass){
		$(e).removeClass(strClass);
	},
	posComments: function(){
		var currentTallest = 0;
		$('#comments-and-quick-links').children().each(function(i){
			Utilities.log($(this).outerHeight(true));
			
			if ($(this).outerHeight(true) > currentTallest) {
				currentTallest = $(this).outerHeight(true);
			}
			$(this).children().each(function(j){
				if ($(this).outerHeight(true) > currentTallest) {
					currentTallest = $(this).outerHeight(true);
				}
			});
		});
		if (parseInt(currentTallest) > $('#comments-and-quick-links').outerHeight(true)) {
			$('#comments-and-quick-links').height(parseInt(currentTallest));
		};
		$('#comments-and-quick-links').children().css({
			'height': currentTallest
		});
	}
};

Truncate = {
	init: function(){
		// multiply $('#adultswim-video-episode-summary').innerWidth() by 2.75
		// to account for the length of text we want to display: 2.75 lines)
		$('#adultswim-video-episode-summary').text($('#adultswim-video-episode-summary').text().replace(/Watch more/g, '	Watch more'));
		$('#adultswim-video-episode-summary').textTruncate($('#adultswim-video-episode-summary').innerWidth() * 2.75, '... <a href="javascript:void(0);" class="more_link">More &#8227;</a>');
		Links.truncate_link();
	}
};
UpNext = {
	strTileNav: '',
	init: function(){
		UpNext.strTileNav = UpNext.convertListToNav(UpNext.returnStrListParent()) + 'TileNav';
		WatchXML.init();
	},
	returnStrListParent: function(){
		return $('section#up-next-content div.up-next-list').attr('id').replace(/-list/,'');
	},
	cleanUpList: function(strCaller){

		$('#' + UpNext.returnStrListParent() + '-row-wrapper ul').each(function(i){
			if($(this).children().length == 0) {
				$(this).remove();
				$('#' + UpNext.returnStrListParent() + '-row-status li:last').remove();
			}
		});
		Watch[UpNext.convertListToNav(UpNext.returnStrListParent()) + 'TileNav'].circleAmnt = $('#' + UpNext.returnStrListParent() + '-row-status li').length;

		if($('#' + UpNext.returnStrListParent() + '-row-wrapper ul').length < 2){
			if ($('#' + UpNext.returnStrListParent() + '-row-wrapper ul:last').children().length < 13) {
				$('#' + UpNext.returnStrListParent() + '-arrow-left').hide();
				$('#' + UpNext.returnStrListParent() + '-arrow-right').hide();
				$('#' + UpNext.returnStrListParent() + '-episodes-all').hide();
				
			}
		}
		DetailedHovers.init();

		
	},
	convertListToNav: function(str){
		function cnvrt(){
			return arguments[0].toUpperCase();
		}
		return str.replace(/\b[a-z]/g, cnvrt).replace(/\-/g, '');
	},
	delegateArrows: function(){
		Watch[UpNext.strTileNav].setup();
		switch ($('#' + UpNext.returnStrListParent() + '-row-status li').length) {
			case 1:
				$('#' + UpNext.returnStrListParent() + '-arrow-left').unbind();
				$('#' + UpNext.returnStrListParent() + '-arrow-right').unbind();
				
				UpNext.bool = true;
				
				break;
			default:
				break;
		}
	},
	singleton: function(){
		// cast Player.strName and Player.strTitle if null
		switch (Player.strName) {
			case null:
			case 'null':
			case undefined:
			case 'undefined':
			case '':
				Player.strName = Utilities.formatLink($('.now-playing').nextAll().eq(1).find('.show a').text());
				break;
			default:
				break;
		}
		switch (Player.strTitle) {
			case null:
			case 'null':
			case undefined:
			case 'undefined':
			case '':
				Player.strTitle = Utilities.formatLink($('.now-playing').nextAll().eq(1).find('.title a').text());
				break;
			default:
				break;
		}
		// check if user wishes to watch next piece of content
		if (Video.continuousEnabled === true) {
			// check if current tab contains now-playing content
			$.cookie(Video._cookie_epCount, parseInt($.cookie(Video._cookie_epCount))+ 1, Video.options);
			if (Player.strName.length === 0 && Player.strTitle.length === 0) {
				// check if there are 18 pieces of content in current tab
				if ($('#' + UpNext.returnStrListParent() + '-row-wrapper ul').children().length === 36) {
					// if so, call next iteration
					if ((((($('.now-playing').index() + 2) / 2)) + ($('.now-playing').parent().index() * 6)) < parseInt($('.up-next-on').attr('data-content-items'))) {
						Player.strName = Utilities.formatLink($('.now-playing').parent().next().find('li:eq(0) .show a').text());
						Player.strTitle = Utilities.formatLink($('.now-playing').parent().next().find('li:eq(0) .title a').text());
						$.cookie(Video._cookie_callUpNext, true, Video.options);
					}
					else {
						Player.strName = Utilities.formatLink($('#' + UpNext.returnStrListParent() + '-row-wrapper ul li:eq(0) .show a').text());
						Player.strTitle = Utilities.formatLink($('#' + UpNext.returnStrListParent() + '-row-wrapper ul li:eq(0) .title a').text());
						$.cookie(Video._cookie_epCount, 0, Video.options);
					}
			// check if .now-playing is the last item in the current list
				} else if ($('#' + UpNext.returnStrListParent() + '-row-wrapper ul').children().length < 3) {
					$.ajax({
						type: 'GET',
						url: "/adultswimdynamic/staged/AS.configuration.xml",
						dataType: 'xml',
						success: function(xml){
							var strNextID = $('#adultswim-video-details').attr('data-collection-id');
							if ($(xml).find("logiccategories collection[id='" + $('#adultswim-video-details').attr('data-collection-id') + "']").next().length > 0) {
								strNextID = $(xml).find("logiccategories collection[id='" + $('#adultswim-video-details').attr('data-collection-id') + "']").next().attr('id');
								
								//Utilities.log($(xml).find("logiccategories collection[id='" + $('#adultswim-video-details').attr('data-collection-id') + "']").next().attr('id') + ' : ' + $(xml).find("logiccategories collection[id='" + $('#adultswim-video-details').attr('data-collection-id') + "']").next().attr('name'));
							} else {
								strNextID = $(xml).find("logiccategories collection[id='" + $('#adultswim-video-details').attr('data-collection-id') + "']").next().attr('id');

								//Utilities.log($(xml).find("logiccategories collection:first").attr('id') + ' : ' + $(xml).find("logiccategories collection:first").attr('name'));
							}
							$.ajax({
								type: 'GET',
								url: '/adultswimdynamic/asfix-svc/episodeSearch/getAllEpisodes?limit=1&offset=0&sortByDate=DESC&categoryName=' + WatchXML.strCategoryName + '&filterByEpisodeType=' + WatchXML.strEpisodeType + '&filterByCollectionId=' + strNextID + '&networkName=AS',
								dataType: 'xml',
								success: function(xml){
									if ($(xml).find("episode").length > 0) {
										Player.strName = Utilities.formatLink($(xml).find("episode").attr('collectionTitle'));
										Player.strTitle = Utilities.formatLink($(xml).find("episode").attr('title'));
									};
									$.cookie(Video._cookie_epCount, 0, Video.options);
								},
								error: function(XMLHttpRequest, textStatus, errorThrown){
									//Utilities.log('AJAX ERROR ' + XMLHttpRequest + ' : ' + textStatus + ' :: ' + errorThrown);
								},
								complete: function(xml){
								}
							})
						},
						error: function(XMLHttpRequest, textStatus, errorThrown){
						},
						complete: function(xml){
						}
					})
				} 
			}
			
			if (Player.strName !== '' && Player.strTitle !== '') {
				window.location.href = '/' + Player.strName + '/' + Player.strTitle + '.html';
			}
			else {
				WatchUtilities.endCard();
			}
		}
		else {
			WatchUtilities.endCard();
		}
	}
};
VideoLinks = {
	init: function(){
		$('.video-list-item').click(function(){
			$.cookie(Video._cookie_epCount, parseInt(parseInt($.cookie(Video._cookie_epCount)) + parseInt($(this).attr('data-episode-count'))), Video.options);
		});
		VideoLinks.setupRollovers();
		VideoLinks.setupDetailHovers(".video-tile-row li:even");
	},
	
	setupRollovers: function(){
		WatchUtilities.parseQSParams();
		$('.video-tile-row li:even').hover(function(){
			$(this).css({
				'background': '#bbf41c'
			});
		}, function(){
			$(this).css({
				'background': $(this).closest('li').hasClass('now-playing') === true ? '#bbf41c' : '#fff'
			});
		});
	},
	
	setupDetailHovers: function(rows){
		$(rows).hover(function(){
			DetailedHovers.showHover($(this));
		}, function(){
			DetailedHovers.hideHover($(this));
		});
	}
};


/* **** COOKIE METHODS **** */
WatchCookies = {
	deleteSniffEpId: function(oElem){
		var strEpId = oElem.children('img').attr('class'); // retrieve ep id from image class
		var regex = /(episode-image )([a-zA-Z0-9]+)/; // regex out string episode-image
		strEpId = strEpId.replace(regex, '$2'); // replace string with just id
		WatchCookies.updateDeletedEpsCookie(strEpId);
	},
	getUpdateupNextTab: function(){
		return $.cookie(Video._cookie_upNextTab);
	},
	setUpdateupNextTab: function(strId){
		$.cookie(Video._cookie_upNextTab, strId, Video.options);
	},
	updateDeletedEpsCookie: function(strEpId){
		switch ($.cookie(Video._cookie_deletedEpisodes)) {
			case '':
			case null:
			case undefined:
				$.cookie(Video._cookie_deletedEpisodes, strEpId, Video.options); // no ids detected: set strEpId to cookie
				break;
			default:
				if ($.cookie(Video._cookie_deletedEpisodes).match(strEpId) === null) {
					$.cookie(Video._cookie_deletedEpisodes, $.cookie(Video._cookie_deletedEpisodes) + '#' + strEpId, Video.options);
				}
				break;
		}
	},
	updateEpisodeCountCookie: function(){
		$.cookie(Video._cookie_epCount, WatchUtilities.getUpNextEpisodeCount(), Video.options);
	}
};

WatchSetup = {
	init: function(){
		pageObj._strCollectionId = WatchUtilities.getCollectionId();
		_strEpId = WatchUtilities.getVideoId(); // video.js
		_strSegId = WatchUtilities.getSegId(0); // video.js
		Video.browserVersion = Number(jQuery.browser.version.split('.')[0]);
		Video._objVidz.url = "/adultswimdynamic/asfix-svc/episodeSearch/getEpisodesByIDs?ids=" + _strEpId + "&networkName=AS";
		Watch._strCollectionId = WatchUtilities.getCollectionId();
		$.ajax({
			type: Watch._strAjaxType,
			url: "/adultswimdynamic/asfix-svc/episodeSearch/getEpisodesByIDs?ids=" + $('#adultswim-video-details').attr('data-episode-id') + "&networkName=AS",
			dataType: 'xml',
			success: function(xml){
				if ($(xml).find('episode').length > 0) {
					$(xml).find('episode').each(function(){
						$('#adultswim-video-details .views span').text(Utilities.commafy($(this).attr('numberOfViews')));
						$('.rating' + $(this).attr('ranking')).addClass('on');
					})
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
			},
			complete: function(xml){
			}
		})
	}
};

WatchUtilities = { /* **** GET IDS **** */
	endCard: function(){
		WatchUtilities.videoOverlay();
		$('#share-overlay').addClass('overlay-endcard').append('<div class="overlay-endcard-span-holder clearfix"><span class="overlay-endcard-span-left"><img src="' + $('meta[property="og:image"]').attr('content') + '" width="120" height="90" class="overlay-endcard-image" alt="' + $('#adultswim-video-episode-title').text() + ' - ' + $('#adultswim-video-collection-title').text() + '"/></span><span class="overlay-endcard-span-right"><p>' + $('#adultswim-video-collection-title').text() + '</p><p>' + $('#adultswim-video-episode-title').text() + '</p><ul class="replay-share-this-video"><li class="replay"><a href="javascript:void(0);">Replay</a></li><li class="share"><a href="javascript:void(0);">Share</a></li><li class="email"><a href="javascript:void(0);">Email</a></li><li class="embed"><a href="javascript:void(0);">Embed</a></li></ul></span></div>');
		
		$('.replay-share-this-video .replay a').click(function(){
			Player.bPause = false;
			Player.pauseVideo();
			$('.overlay').each(function(){
				$(this).remove();
			});
		});
		$('.replay-share-this-video .email a').click(function(){
			Share.shareSocial($(this));
		});
		/* */
		$('.replay-share-this-video .share a').click(function(){
			Share.shareSocial($(this));
		});
		$('.replay-share-this-video .embed a').click(function(){
			Share.shareSocial($(this));
		});
		/* */
	},
	getCollectionId: function(){
		return $('#adultswim-video-details').attr('data-collection-id');
	},
	getSegId: function(nSeg, strHashList){
		var s;
		
		switch (strHashList) {
			case null:
			case undefined:
			case '':
				s = $('#adultswim-video-details').attr('data-segment-ids');
				break;
			default:
				s = strHashList;
				break;
		}
		if (nSeg === 0) {
			Video._arrSegIds = s.split('#');
			Video._nSegArrLen = Video._arrSegIds.length;
		}
		else {
			s = Video._arrSegIds[nSeg];
		}
		return s;
	},
	getUpNextEpisodeCount: function(){
		var str = '';
		$('#up-next section').each(function(i){
			str === '' ? str = $(this).attr('id') + ':' + $(this).attr('data-content-items') : str += '#' + $(this).attr('id') + ':' + $(this).attr('data-content-items');
		})
		return str;
	},
	getVideoId: function(){
		return $('#adultswim-video-details').attr('data-episode-id');
	},
	getDuration: function(nSeg, strHashList){
		var s;
		try {
			switch (strHashList) {
				case null:
				case undefined:
				case '':
					s = $('#adultswim-video-details').attr('data-segment-durations');
					break;
				default:
					s = strHashList;
					break;
			}
			if (nSeg === 0) {
				Video._arrDuration = s.split('#');
			}
			s = Video._arrDuration[nSeg];
		} 
		catch (e) {
			s = null;
		}
		return s;
	},
	getParameterByName: function(name){
		name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
		var regexS = "[\\?&]" + name + "=([^&#]*)";
		var regex = new RegExp(regexS);
		var results = regex.exec(window.location.href);
		if (results == null) 
			return "";
		else 
			return decodeURIComponent(results[1].replace(/\+/g, " "));
	},
	parseQSParams: function(param){
		switch (WatchUtilities.getParameterByName('auxUpNext')) {
			case 'on':
				WatchUtilities.turnOnCutItOut();
				break;
			default:
				break;
		}
		switch (WatchUtilities.getParameterByName('behavior')) {
			case 'next-tab':
				break;
			case 'next-tab-featured':
				break;
			default:
				break;
		}
	},
	makeTime: function(oTime){
		if (!/:/i.test($(oTime).text())) {
			var t = Number($(oTime).text());
			$(this).data('original', t);
			var h = Math.floor(t / 3600);
			t %= 3600;
			var m = Math.floor(t / 60);
			var s = Math.round(t % 60);
			$(oTime).text((h > 0 ? h + ':' : '') + (((m < 10) ? '0' + m : m) + ':' + ((s < 10) ? '0' + s : s)));
		}
	},
	stringify: function(obj){
		var str = new String(obj);
		return (str);
	},
	turnOnCutItOut: function(){
		$('#up-next-episodes-row-wrapper ul:first li:first .cutItOut').css({
			'display': 'block'
		});
		$('#up-next-clips-row-wrapper ul:first li:first .cutItOut').css({
			'display': 'block'
		});
	},
	videoOverlay: function(){
		if ($('.overlay').length === 0) {
			$('#pod6').append('<div class="overlay"></div>');
		}
		if ($('#share-overlay').length === 0) {
			var str = '';
			$('#pod6').append('<div id="share-overlay" class="overlay"></div>');
			$('#share-overlay').append('<a href="javascript:void(0);" class="close-overlay"></a>');
			$('.overlay').css({
				'position': 'absolute',
				'color': '#fff',
				'z-index': '98',
				'height': $('#pod6 object').outerHeight(),
				'width': $('#pod6 object').outerWidth()
			});
			
			WatchUtilities.videoOverlayStyles();
			$('#share-overlay').css({
				'z-index': '99'
			});
			$('.close-overlay').click(function(){
				$('.overlay').each(function(){
					$(this).remove();
				});
				if (Player.bPlayEnded) {
					Player.playIt();
				}
				else {
					Player.bPause = false;
					Player.pauseVideo();
				}
			});
		}
		else {
			$('#share-overlay').remove();
			WatchUtilities.videoOverlay();
		}
	},
	videoOverlayStyles: function(){
		try {
		
			$('.overlay').css({
				'top': $('#pod6 object').position().top,
				'left': $('#pod6 object').position().left
			});
		} 
		catch (e) {
			////////////Utilities.log('videoOverlayStyles error: ' + e.name + ' : ' + e.message);
		}
	}
};
WatchXML = {
	nItemLimit: 18,
	nUpdateUpNextCollectionCount: 0,
	strCategoryName: $('#adultswim-video-details').attr('data-category-type'),
	strCollectionId: $('#adultswim-video-details').attr('data-collection-id'),
	strEpisodeType: 'PRE,EPI,CLI',
	strSortByEpisodeRanking: '',
	init: function(){

		if (Watch._bGetOutTheVote) {
			Video._objVidz.url = '/adultswimdynamic/asfix-svc/services/postRating?id=' + WatchUtilities.getVideoId() + '&rating=' + Watch._strVote + '&networkName=AS';
		}
		else {
			var episodeRanking = WatchXML.strSortByEpisodeRanking == '' ? WatchXML.strSortByEpisodeRanking : '&sortByEpisodeRanking=' + WatchXML.strSortByEpisodeRanking;
			
			Video._objVidz.url = '/adultswimdynamic/asfix-svc/episodeSearch/getAllEpisodes?limit=' + WatchXML.nItemLimit + '&offset=' + $.cookie(Video._cookie_epCount) + '&sortByDate=DESC&categoryName=' + WatchXML.strCategoryName + '&filterByEpisodeType=' + WatchXML.strEpisodeType + '&filterByCollectionId=' + WatchXML.strCollectionId + episodeRanking + '&networkName=AS';
		}
		$.ajax({
			type: Watch._strAjaxType,
			url: Video._objVidz.url,
			dataType: 'xml',
			success: function(xml){
				if (!Watch._bGetOutTheVote) {
					WatchXML.parseEpisodeXML(xml);
					//Utilities.log('!!!!!!SUCCESS!');
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
				//Utilities.log('AJAX ERROR ' + XMLHttpRequest + ' : ' + textStatus + ' :: ' + errorThrown);
			},
			complete: function(xml){
				//Utilities.log('!!!!!!COMPLETE!');
				if (Watch._bGetOutTheVote) {
					Watch._strAjaxType = 'GET';
					Watch._bGetOutTheVote = false;
				}
				
				UpNext.cleanUpList();
				if (WatchXML.bUpdateUpNextCollection) {
					if (WatchXML.nUpdateUpNextCollectionCount == 0) {
						WatchXML.nUpdateUpNextCollectionCount = 1;
						WatchXML.init();
					}
					else {
						WatchXML.nUpdateUpNextCollectionCount = 0;
						WatchXML.bUpdateUpNextCollection = false;
					}
				}
			}
		}); // close $.ajax
	},
	parseEpisodeXML: function(xml){
		$('#' + UpNext.returnStrListParent() + '-row-wrapper ul').each(function(){
			$(this).empty();
		});
		if ($(xml).find('episode').length > 0) {
			if ($(xml).find('episode').length > 12) {
				$('#' + UpNext.returnStrListParent() + '-arrow-left').show();
				$('#' + UpNext.returnStrListParent() + '-arrow-right').show();
				$('#' + UpNext.returnStrListParent() + '-episodes-all').show();
			}
			$(xml).find('episode').each(function(i){
				i++;
				
				//Utilities.log('|-o-| |-o-| Math.ceil(i/6): ' + Math.ceil(i / 6) + ' : ' + $(this).attr('title'));
				$('#' + UpNext.returnStrListParent() + '-row-' + Math.ceil(i / 6)).append('<li class="video-list-item" data-episode-id="' + $(this).attr('id') + '" data-episode-count="' + (i - 1) + '"><span class="cutItOut"><a href="javascript:void(0);"></a></span><a href="' +
				$(this).find('episodeLink').attr('episodeUrl').replace(/http:\/\/video\.adultswim\.com/,'') +
				'"><img alt="' +
				$(this).attr('collectionTitle') +
				' - ' +
				$(this).attr('title') +
				'" width="120" height="90" src="' +
				$(this).attr('seoThumbnailUrl') +
				'" /></a><a href="' +
				$(this).find('episodeLink').attr('episodeUrl').replace(/http:\/\/video\.adultswim\.com/,'') +
				'" class="sash ' +
				$(this).attr('episodeType') +
				'"></a><h4 class="show"><a href="' +
				$(this).find('episodeLink').attr('episodeUrl').replace(/http:\/\/video\.adultswim\.com/,'') +
				'">' +
				$(this).attr('collectionTitle') +
				'</a></h4><p class="title"><a href="' +
				$(this).find('episodeLink').attr('episodeUrl').replace(/http:\/\/video\.adultswim\.com/,'') +
				'">' +
				$(this).attr('title') +
				'</a></p><p class="views"><a href="' +
				$(this).find('episodeLink').attr('episodeUrl').replace(/http:\/\/video\.adultswim\.com/,'') +
				'">Views: ' +
				$(this).attr('numberOfViews') +
				'</a></p><p class="ranking-rating"><a href="' +
				$(this).find('episodeLink').attr('episodeUrl').replace(/http:\/\/video\.adultswim\.com/,'') +
				'"><span class="ranking">Rating ' +
				$(this).attr('ranking') +
				'</span><span class="rating">' +
				$(this).attr('rating') +
				'</span></a></p></li>' +
				'<li class="detailed-hover detailed-hover-' +
				i +
				'">' +
				'<div class="detailed-hover-arrow"></div>' +
				'<div class="detailed-hover-border"></div>' +
				'<div class="detailed-hover-border-bottom"></div>' +
				'<h3><span class="bold">' +
				$(this).attr('collectionTitle') +
				':</span>' +
				$(this).attr('title') +
				'</h3>' +
				'<p>' +
				$(this).attr('epiSeasonName') +
				'</p>' +
				'<p>Expiration Date: ' +
				$(this).attr('expirationDate') +
				'<span> | </span> Rated: ' +
				$(this).attr('rating') +
				'</p>' +
				'<p>Rating: ' +
				$(this).attr('ranking') +
				'</p>' +
				'<hr/>' +
				'<p>' +
				$(this).find('description').text() +
				'</p>' +
				'</li>');
				
				switch ((i / 2 % 3)) {
					case 0.5:
					case 1:
					case 1.5:
						$('.detailed-hover-' + i).addClass('hover-left');
						$('.detailed-hover-' + i + ' .detailed-hover-arrow').removeClass('detailed-hover-arrow').addClass('detailed-hover-left-arrow');
						$('.detailed-hover-' + i + ' .detailed-hover-border').removeClass('detailed-hover-border').addClass('detailed-hover-border-right');
						break;
					default:
						$('.detailed-hover-' + i).addClass('hover-right');
						$('.detailed-hover-' + i + ' .detailed-hover-arrow').removeClass('detailed-hover-arrow').addClass('detailed-hover-right-arrow');
						$('.detailed-hover-' + i + ' .detailed-hover-border').removeClass('detailed-hover-border').addClass('detailed-hover-border-left');
						break;
				}
				$('.detailed-hover-' + i).removeClass('detailed-hover-' + i);
			});
			var nRow = 3;
			var nItem = 6;
			if ($.cookie(Video._cookie_epCount) % 6 !== 0) {
				nItem = $.cookie(Video._cookie_epCount) % 6;
			}
			if (Math.ceil($.cookie(Video._cookie_epCount) / 6) % 3 !== 0) {
				nRow = Math.ceil($.cookie(Video._cookie_epCount) / 6) % 3;
			}
//			alert(Utilities.formatLink($('#adultswim-video-collection-title').text()) + "/" + Utilities.formatLink($('#adultswim-video-episode-title').text()));
			if($(".video-list-item a[href='/" + Utilities.formatLink($('#adultswim-video-collection-title').text()) + "/" + Utilities.formatLink($('#adultswim-video-episode-title').text()) + ".html']").length > 0) {
				$(".video-list-item a[href='/" + Utilities.formatLink($('#adultswim-video-collection-title').text()) + "/" + Utilities.formatLink($('#adultswim-video-episode-title').text()) + ".html']").closest('li').addClass('now-playing');

				$.cookie(Video._cookie_epCount, $(".video-list-item a[href='/" + Utilities.formatLink($('#adultswim-video-collection-title').text()) + "/" + Utilities.formatLink($('#adultswim-video-episode-title').text()) + ".html']").closest('li').attr('data-episode-count'), Video.options);

			}
			

			VideoLinks.setupRollovers();
			$('#' + UpNext.returnStrListParent() + '-row-1 li.video-list-item:last').addClass('last');
			$('#' + UpNext.returnStrListParent() + '-row-2 li.video-list-item:last').addClass('last');
			$('#' + UpNext.returnStrListParent() + '-row-3 li.video-list-item:last').addClass('last');
			$('#' + UpNext.returnStrListParent() + '-row-status .last').removeClass('last');
			$('#' + UpNext.returnStrListParent() + '-row-status li:last').addClass('last');
			WatchXML.bItemsEmpty = false;
			VideoLinks.init();
		}
		else {
			WatchXML.bItemsEmpty = true;
		}
	}

};

