/* *
 * @author aschillinger
 * version 65
 */
$(document).ready(function(){
	Player.init();
});

Player = {
	_nSeg: 0,
	attributes: {},
	bAutoRewind: false,
	bMute: '',
	bNext: '',
	bPause: false,
	bPrev: '',
	bUpNextFail: false,
	flashvars: {},
	intFlash: '',
	oEvent: {},
	objNowPlaying: null,
	params: {},
	intPlayIt: '',
	sitePlayer: true,
	promoPlayerIds: {},
	
	init: function(){
		////Utilities.log('_PC init');
		Player.flashvars = {
			configURL: Player.getConfigURL(),
			JSEventHandler: pageObj.JSEventHandler
		};
		Player.params = {
			allowscriptaccess: 'always',
			allownetworking: 'all',
			allowfullscreen: true,
			base: pageObj.playerBase
		};
		Player.attributes = {
			id: pageObj.playerID,
			name: pageObj.playerID
		};
		var width = "640";
		var height = "360";
		
		// check if is a browse/landing/index page
		if (!Video.bWatchPlayer) {
			width = "260";
			height = "146";
		}
		Utilities.log('|-o-| 0 Player.flashvars: ' + Player.flashvars);
		for(var x in Player.flashvars){
			Utilities.log('|-o-| 1 Player.flashvars[' + x + ']: ' + Player.flashvars[x]);
		}
		Utilities.log('|-o-| 2 Player.flashvars.configURL: ' + Player.getConfigURL());
		Utilities.log('|-o-| 3 Player.flashvars.JSEventHandler: ' + pageObj.JSEventHandler);
		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;
	},
	
	getURI: function(){
		////Utilities.log('_PC getURI');
		var u = location.href;
		return u;
	},
	getTitle: function(strType){
		////Utilities.log('_PC getTitle');
		var t = null;
		var s = $('.adultswim-video-title').text();
		var a = s.split(':');
		switch (strType) {
			case 'collection':
				t = jQuery.trim(a[0]);
				break;
			case 'episode':
				t = jQuery.trim(a[1]);
				break;
			default:
				break;
		}
		return t;
	},
	playIt: function(str){
		//alert('@@ ' + str + ' : ' + Video.bWatchPlayer + ' :: ' + Video._nSegArrLen);
		if (!Video.bWatchPlayer) {
			try {
				if ($('.nowPlaying').attr('class') === undefined) {
					Player._nSeg = 0;
					if (Utilities.getContentType() == 'CLI') {
						Video._nSegArrLen = 0;
					} else {
						Video._nSegArrLen = Player.objNowPlaying.find('.thumbnail').attr('class').split(' ').length;
					}
				}
			} catch (e) {
				Player._nSeg = 0;
				if (Utilities.getContentType() == 'CLI') {
					Video._nSegArrLen = 0;
				} else {
					Video._nSegArrLen = Player.objNowPlaying.find('.thumbnail').attr('class').split(' ').length;
				}
			}
		}
		////Utilities.log('_PC_playIt ' + Player._nSeg + ', ' + Video._nSegArrLen + ' : ' + str);
		if (str === 'prev') {
			//iterate back twice -- once to compensate for this video and again to call up previous episode
			Player._nSeg--;
			Player._nSeg--;
		}
		try {
			//alert(Video._nSegArrLen + ' : ' + Player._nSeg + ' :: ' + str + ' ::: ' + pageObj.continuousEnabled + ' : ' + Video.bWatchPlayer);
			clearInterval(Player.intPlayIt);
			Utilities.log('Player.intPlayIt cleared');
		} catch (e) {
			Utilities.log('clearInt error ' + e.message);
		}
		switch (Video._nSegArrLen) {
			case Player._nSeg:
				Utilities.log('case ' + Player._nSeg + ' : ' + pageObj.continuousEnabled);
				if (Player._nSeg > 0) {
					Utilities.log('> 0');
					switch (str) {
						case 'prev':
							break;
						case 'next':
							Utilities.log('NEXTEP!');
							Player.nextEpisode(null, null);
							break;
						default:
							if (pageObj.continuousEnabled) {
								Player.nextEpisode(null, null);
							}
							break;
					}
				}
				break;
			default:
				Utilities.log('|@| pageObj.sectionID ' + pageObj.sectionID);
				if (Video.bWatchPlayer) {
					
					try{Utilities.log('|-o-| 0 ' + Player._nSeg);}catch(e){Utilities.log('error |-o-| 0 ' + e.name + ' :: ' + e.message);};
					try{Utilities.log('|-o-| 1 ' + WatchUtilities.getSegId(Player._nSeg));}catch(e){Utilities.log('error |-o-| 1 ' + e.name + ' :: ' + e.message);};
					try{Utilities.log('|-o-| 2 ' + WatchUtilities.getVideoId());}catch(e){Utilities.log('error |-o-| 2 ' + e.name + ' :: ' + e.message);};
					try{Utilities.log('|-o-| 3 AS-' + WatchUtilities.getVideoId());}catch(e){Utilities.log('error |-o-| 3 ' + e.name + ' :: ' + e.message);};
					try{Utilities.log('|-o-| 4 ' + strPageName.replace(/&#039;/g,"'"));}catch(e){Utilities.log('error |-o-| 4 ' + e.name + ' :: ' + e.message);};
					try{Utilities.log('|-o-| 5 ' + pageObj.episodeType);}catch(e){Utilities.log('error |-o-| 5 ' + e.name + ' :: ' + e.message);};
					try{Utilities.log('|-o-| 6 ' + strSubSectionName.replace(/&#039;/g,"'"));}catch(e){Utilities.log('error |-o-| 6 ' + e.name + ' :: ' + e.message);};
					try{Utilities.log('|-o-| 7 ' + WatchUtilities.getCollectionId());}catch(e){Utilities.log('error |-o-| 7 ' + e.name + ' :: ' + e.message);};
					try{Utilities.log('|-o-| 8 ' + Player.getURI());}catch(e){Utilities.log('error |-o-| 8 ' + e.name + ' :: ' + e.message);};
					try{Utilities.log('|-o-| 9 ' + pageObj.sectionID);}catch(e){Utilities.log('error |-o-| 9 ' + e.name + ' :: ' + e.message);};
					try{Utilities.log('|-o-| 10 ' + WatchUtilities.getDuration(Player._nSeg));}catch(e){Utilities.log('error |-o-| 10 ' + e.name + ' :: ' + e.message);};
					try{Utilities.log('|-o-| 11 ' + $('.adultswim-video-data .rating').text());}catch(e){Utilities.log('error |-o-| 11 ' + e.name + ' :: ' + e.message);};
					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: ' + Utilities.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: ' + Utilities.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: ' + Utilities.getCollectionId());
						Utilities.debug('|-o-| videoPageURL: ' + Player.getURI());
						Utilities.debug('|-o-| sectionID: ' + pageObj.sectionID);
						Utilities.debug('|-o-| duration: ' + Utilities.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: Utilities.getSegId(Player._nSeg, Player.promoPlayerIds.segIdList),
								episodeID: $('.nowPlaying .thumbnail img').attr('class'),
								customID: 'AS-' + Utilities.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: Utilities.getCollectionId(),
								videoPageURL: Player.getURI(),
								sectionID: pageObj.sectionID,
								duration: Utilities.getDuration(Player._nSeg, $('.nowPlaying .duration').attr('class').replace('duration ', '')),
								rating: $('.nowPlaying').find('.rating').text()
						});
					} catch (e) {
						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();
						
					/*
					 Player._nSeg = 0;
					 Browse.getSegId();
					 Player.playVideo({
					 segmentIndex: Player._nSeg,
					 segmentID: Utilities.getSegId(Player._nSeg, Player.promoPlayerIds.segIdList),
					 episodeID: $('.nowPlaying .thumbnail img').attr('class'),
					 customID: 'AS-' + Utilities.getVideoId(),
					 title: $('.nowPlaying').find('.episode-title').text(),//Player.getTitle('episode'),
					 contentType: Utilities.getContentType(),
					 collectionTitle: $('.nowPlaying').find('.episode-name').text(),//Player.getTitle('collection'),
					 collectionID: Utilities.getCollectionId(),
					 videoPageURL: Player.getURI(),
					 sectionID: pageObj.sectionID,
					 duration: Utilities.getDuration(Player._nSeg, $('.nowPlaying .duration').attr('class').replace('duration ', '')),
					 rating: $('.nowPlaying').find('.rating').text()
					 });
					 */
					}
				//					}
				}
				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;
		}
	},
	setPromoPlayerIds: function(videoId, segIdList){
		Player.promoPlayerIds.videoId = videoId;
		Player.promoPlayerIds.segIdList = segIdList;
	},
	nextEpisode: function(strName, strTitle){
		alert('_PC nextEpisode0 ' + strName + ', ' + strTitle + ' : ' + WatchUtilities.getVideoId() + ' : ' + Video.bWatchPlayer);
		if (Video.bWatchPlayer) {
			try {
				WatchCookies.updateDeletedEpsCookie(WatchUtilities.getVideoId());
				WatchCookies.updateEpisodeCountCookie();
			} catch (e) {
				alert('_PC watchcookie error: ' + e.name + ' : ' + e.message);
			}
			switch (strName) {
				case null:
				case 'null':
				case undefined:
				case 'undefined':
				case '':
					strName = Utilities.formatLink($('.up-next-on li:first .show a').text());
					break;
				default:
					break;
			}
			switch (strTitle) {
				case null:
				case 'null':
				case undefined:
				case 'undefined':
				case '':
					strTitle = Utilities.formatLink($('.up-next-on li:first .title a').text());
					break;
				default:
					break;
			}
			Utilities.log('_PC nextEpisode -> ' + strName + ' : ' + strTitle);
//			if ($('.all-my-episodes .are-belong-to-you li:first').attr('id') != 'next-episode-z') {
				window.location.href = '/' + strName + '/' + strTitle + '.html';
//			}
		} else {
			Utilities.debug('{-o-}')
			try {
				Utilities.debug('{-oo-}')
				//				Browse.itemCount = 0;
				////Utilities.log('getting segId...');
				BrowseUtilities.init();
			} catch (e) {
					Utilities.debug('000error ' + e.name + ' : ' + e.message)
			};
		
		}
	},
	playVideo: function(p_context){
		for (var x in p_context){
			//Utilities.log('|-o-| p_context[' + x + '] ' + p_context[x] + '\n')
		}
		//Utilities.log('p_context: \n\tsegmentIndex: ' + p_context.segmentIndex + '\n\tsegmentID: ' + p_context.segmentID + '\n\tepisodeID: ' + p_context.episodeID + '\n\ttitle: ' + p_context.title + '\n\tcontentType: ' + p_context.contentType + '\n\tcollectionTitle: ' + p_context.collectionTitle + '\n\tcollectionID: ' + p_context.collectionID + '\n\tvideoPageURL: ' + p_context.videoPageURL + '\n\tsectionID: ' + p_context.sectionID + '\n\tduration: ' + p_context.duration + '\n\trating: ' + p_context.rating);
		swfobject.getObjectById(pageObj.playerID).setMedia(p_context);
	},
	pauseVideo: function(){
		////Utilities.log('pause1: ' + pageObj.playerID);
		////Utilities.log('pause2: ' + swfobject.getObjectById(pageObj.playerID));
		////Utilities.log('pause0: ' + Player.bPause);
		
		(Player.bPause) ? swfobject.getObjectById(pageObj.playerID).pauseMedia() : swfobject.getObjectById(pageObj.playerID).playMedia();
	},
	
	onPlayerEvent: function(p_event){
		Player.eventType = p_event.type;
		////alert('!! ' + p_event.type + ' : ' + Player.eventType);
		Utilities.debug('_PC event ' + Player.eventType);
		switch (p_event.type) {
		
			// player
			case 'playerInitSucceeded':
				////Utilities.log('_PC event: playerInitSucceeded');
				pageObj.initialized = true;
				PlayerButtons.setMuteEnabled();
				if (jQuery.browser.msie && Video.browserVersion < 7) {
					Player.intPlayIt = setInterval(Player.playIt(), 1000);
				} else {
					Player.playIt();
				}
				break;
			case 'contentPlayEnded':
				pageObj.initialized = true;
				////Utilities.log('_PC event: contentPlayEnded');
				if (jQuery.browser.msie && Video.browserVersion < 7) {
					Player.intPlayIt = setInterval(Player.playIt(), 1000);
				} else {
					Player.playIt();
				}
				break;
				
			//clicks
			case 'continuousPlaySet':
				pageObj.continuousEnabled = p_event.data;
				try {
					$.cookie(Video._cookie_continuousEnabled, pageObj.continuousEnabled, Video.options);
				} catch (e) {
					//alert('vp1 ' + e.name + ' : ' + e.message);
				}
				break;
			case 'nextClicked':
				Player.playIt('next');
				break;
			case 'previousClicked':
				Player.playIt('prev');
				break;
			case 'muteStateChanged':
				////Utilities.log('_PC event: muteStateChanged ' + $.cookie(Video._cookie_bMuted));
				if ($.cookie(Video._cookie_bMuted)) {
					$.cookie(Video._cookie_bMuted, false, Video.options);
				////Utilities.log('_PC event: muteStateChanged ' + $.cookie(Video._cookie_bMuted));
				}
				PlayerButtons.setMuteEnabled();
				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':
				Utilities.log('Oh succotash! contentPlaylistFailed:');
				Utilities.log('{-o-} pageObj.playerID: ' + pageObj.playerID);
				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;
			//default
			default:
				Utilities.log('default p_event.type ' + p_event.type);
				break;
		}
	},
	alertPlayer: function(message){
		////Utilities.log('_PC_Watch.bActive_1 ' + Watch.bActive);
		if (message === 'contentDeactive') {
			//alert('THIS VIDEO HAS BEEN DEACTIVATED');
		}
	}
	
};
PlayerButtons = {
	nextEnabled: function(nextEnabled){
		////Utilities.log('NE: ' + nextEnabled + ' : ' + pageObj.nextEnabled);
		swfobject.getObjectById(pageObj.playerID).setNextEnabled(nextEnabled);
	},
	setPrevEnabled: function(prevEnabled){
		////Utilities.log('PE: ' + prevEnabled + ' : ' + pageObj.prevEnabled);
		swfobject.getObjectById(pageObj.playerID).setPreviousEnabled(prevEnabled);
	},
	setContinuousEnabled: function(){
		////Utilities.log('CE: ' + $.cookie(Video._cookie_continuousEnabled));
		try {
			swfobject.getObjectById(pageObj.playerID).setContinuousPlaySelected($.cookie(Video._cookie_continuousEnabled))
		} catch (e) {
		};
			},
	setMuteEnabled: function(){
		////Utilities.log('setMuteEnabled: ' + $.cookie($.cookie(Video._cookie_bMuted)));
		($.cookie(Video._cookie_bMuted) == 'true') ? Player.bMute = true : Player.bMute = false;
		try {
			swfobject.getObjectById(pageObj.playerID).setMuted(Player.bMute)
		} catch (e) {
			////Utilities.log('setMuteEnabled error ' + e.name + ' : ' + e.message);
		};
	}
};

