var CookieJar = {
	cookie_name: 'TVEnp',
	cookie_name_id: 'TVEid',
	cookie_name_collection: 'TVEcollection',
	cookie_name_page: 'TVEpage'
};

var driver = driver || "";
var handleAddPlaylistItem = handleAddPlaylistItem || function() {};
var cvpReady = false;
var waitingVideo = "";
var navXml = "";
var currentVideoId = "";
var queueVideoId = "";
var currentVideoObj = {};
var currentSceneId = "";
var currentSectionMap = {};
var currentTeaserMap = {};
var relatedTeaserMap = {};
var grouperTeaserMap = {};
var currentTodaysTopMap = {};
var currentPlaylistMap = {};
var currentFriendsMap = {};
var currentScenesArray = [];
var deepLinkedVideo = deepLinkedVideo || "";
var deepLinkedCategory = deepLinkedCategory || "";
var lastTrackedVideo = {};
var player = {};

var nAllEpisodesCollectionId = 49050;
//var strCOOKIE_LIST = 'COOKIE_NAME,COOKIE_NAME_id,COOKIE_NAME_collection,COOKIE_NAME_page';
var COOKIE_VAL_collection = $.cookie(CookieJar.cookie_name_collection) == null ? nAllEpisodesCollectionId : $.cookie(CookieJar.cookie_name_collection);
var COOKIE_VAL_page = $.cookie(CookieJar.cookie_name_page) == null ? 1 : $.cookie(CookieJar.cookie_name_page);
var options = { path: '/'};

$(document).ready(function(){
	// initialize the page
	var o = 0;
	
	//////Utilities.log("here")
	
	Dramavision.init();
	
	
	//$('.dramavisionNavItem').corner("top");


});
//var authBool;
var pathArray = window.location.pathname.split('/');
var newPathname = pathArray[2];

Browse = {
	_nTotalPages: 1,
	_objVidz: {},
	bOverrideBlur: false, // boolean to override blur action when user hits enter
	bOverrideNP: false,
	bOverrideVid: false,
	collection: {},
	itemCount: 0,
	itemTotal: 1,
	maxItemsPerPage: 100,//19,
	MaxVideos: 100,//20, //http://staging.adultswim.tv/astv/mvpd/services/getCollectionByContentId.do?offset=0&limit=200&id=49053
	pageNumber: COOKIE_VAL_page,
	strDirection: '',//used for next prev btns
	strFilterOn: 'recent',//used for filter buttons
	strPagination:'',
	strCurrCollection: '',
	videoId: {},
	newvid:{},
	uri: '',
	xmlObj: {},

	init: function(){
		$('#logoBox a').click(function(){
			if(authBool){
				//when user clicks top cap, clear cookies
				Utilities.cookieMonster();
				//and remove cvp
				//$('#adultswim-video-body').hide();
				//showMarketingSWF();
				document.location.reload();
			}

		});
	},
	updatePage: function(num){
		//Utilities.log('111 @@@ ### updatePage ' + num + ' : ' + Browse.strPagination + ' :: ' + Browse.pageNumber);
		switch (num) {
			case '':
			case '0':
				$('.pageNo').val(Browse.strPagination);
				break;
			default:
				if (parseInt(num) > Browse._nTotalPages) {
					$('.pageNo').val(Browse.strPagination);
				} else {
					Browse.pageNumber = parseInt(num);
					Browse.strDirection='';
//					Browse.addVideos();
					//alert(COOKIE_VAL_collection + ' :: ' + Browse.strCurrCollection);
					TeaserArea.loadVideos(COOKIE_VAL_collection);//Browse.strCurrCollection
				}
				break;
		}
	}
}
var Dramavision = {
	PageUrl: 'http://staging.cartoonnetwork.com/' + newPathname,
	NavUrl: '/cntv/mvpd/services/getCollections.do?id=49766',
	CollectionUrl: '/cntv/mvpd/services/getCollectionByContentId.do',//?offset=0&limit=200&id=49053
	RelatedUrl: '',
	GrouperUrl: 'cntv/mvpd/services/cvpXML.do',
	VideoJsonUrl: '',
	SendToFriendUrl: '',
	SearchUrl: '',
	TodaysTopId: COOKIE_VAL_collection, //'39573',
	strBgColor: '#000000',
	
	init: function(){

		Browse.init()
		$.ajax({
			type: "GET",
			url: Dramavision.NavUrl,
			cache: true,
			dataType: "xml",
			success: function(data){
				//////Utilities.log("success"+data)
				navXml = data;
				
				if (waitingSection !== "") {
					// if there was a section waiting for the nav to load, load it now
					//////Utilities.log("in waitingSection"+waitingSection)
//					SectionNav.load(waitingSection);
					
				}
			},
			error: function(){
				Utilities.log("DVinit error")
			}
		});
		BrowseButtons.setupClicks();
		
	},
	playVideo: function(videoId, teaserMap){
		currentVideoId = videoId;
		queueVideoId = null;
		currentPlaylistMap = teaserMap;
		////Utilities.log("playVido0: " + videoId);
		////Utilities.log("playVido1: " + teaserMap[videoId].segments);
		

		switch(teaserMap[videoId]){
			case null:
			case undefined:
			case '':
				$('#videoTitle').empty();
				$('#videoexpirationDate').empty();
				$('#videoBlurb').empty();
//				$("#shareContent input[@type='hidden']")[0].value = "";
//				$("#linkContent textarea")[0].value = "";
//				$("#embedContent textarea")[0].value = "";
				break;
			default:
				//Utilities.log("[-oo-] " + teaserMap[videoId] + ' :: ' + teaserMap[videoId].showTitle);
			
				currentVideoObj = teaserMap[videoId];
				// check for scenes; if they exist, play the first one; if no scenes, play the video
				if (teaserMap[videoId].segments.length > 0) {
					currentScenesArray = teaserMap[videoId].segments;
					
					Scenes.load(teaserMap[videoId].segments);
					//////Utilities.log("before playScene"+currentScenesArray[0].videoId)
					Dramavision.playScene(currentScenesArray[0].videoId);
					//////Utilities.log("after playScene")
				
				} else {
					currentScenesArray = [];
					//////Utilities.log("in else")
					Scenes.empty();
					Dramavision.playScene(videoId);
				}
				
				var myvid = teaserMap[videoId];
				var myvidurl = Dramavision.PageUrl + "?oid=" + videoId;
				
				// close video button area
				// $("#videoButtonArea").slideUp(200);
				//VideoButtons.reset();
				
				// fill in video info
//				$('#videoThumb').html('<img width="96" height="72" src="'+myvid.thumb+'">');
				$('#videoTitle').html('<span class="showTitle">' + myvid.showTitle + '</span>: <span class="episodeTitle">' + myvid.episodeTitle + '</span>');
				$('#ancillary').html('<div id="hd" title="HD">&nbsp;</div><span class="expiration">Expires ' + myvid.expirationDate + '</span><span class="rating">' + myvid.rating + '</span>');
				$('#whatItsAbout').html(myvid.description);
				//$('#videoexpirationDate').html(myvid.episodeTitle);
				//$('#videoBlurb').html(myvid.description);
				
				// populate share, link, embed forms
				//$("#shareContent input[@type='hidden']")[0].value = myvidurl + "%26eref=sharethisEmail";
				//$("#linkContent textarea")[0].value = myvidurl + "&eref=sharethisUrl";
				
				// set the bookmark values
				//var bookMarkTitle = myvid.title + " on TBS.com";
				//if ($("#deliciousForm input[@type='hidden']")[0]) {
				//  $("#deliciousForm input[@type='hidden']")[0].value = myvidurl + "&eref=sharethisDelicious";
				// $("#deliciousForm input[@type='hidden']")[1].value = bookMarkTitle;
				
				//$("#diggForm input[@type='hidden']")[0].value = myvidurl + "&eref=sharethisDigg";
				// $("#diggForm input[@type='hidden']")[1].value = bookMarkTitle;
				//
				//              $("#facebookForm input[@type='hidden']")[0].value = myvidurl + "&eref=sharethisFacebook";
				//            $("#facebookForm input[@type='hidden']")[1].value = bookMarkTitle;
				//
				//              $("#simpyForm input[@type='hidden']")[0].value = myvidurl + "&eref=sharethisSimpy";
				//            $("#simpyForm input[@type='hidden']")[1].value = bookMarkTitle;
				//}
				
				// highlight the playing video
				TeaserArea.highlightPlaying();
				$("#hdBtnBox").click(function () {
//					alert('click!')
					hqReady();
				});

			break;
		}
	},
	playNext: function(){
		// find the next video id for playing one after another
		
		// play the next scene if one exists
		var sceneReached = false;
		if (currentScenesArray.length > 0) {
			for (var i = 0; i < currentScenesArray.length; i++) {
				if (sceneReached) {
					Dramavision.playScene(currentScenesArray[i].videoId);
					return;
				}
				if (currentScenesArray[i].videoId == currentSceneId) {
					sceneReached = true;
				}
			}
		}
		
		// play the next video
		var videoReached = false;
		if (currentPlaylistMap.orderArray != undefined) {
			for (var i = 0; i < currentPlaylistMap.orderArray.length; i++) {
				if (videoReached) {
					//Utilities.log('00000');
					Dramavision.playVideo(currentPlaylistMap.orderArray[i], currentPlaylistMap);
					break;
				}
				if (currentPlaylistMap.orderArray[i] == currentVideoId) {
					videoReached = true;
				}
			}
		}
	},
	playScene: function(videoId){

		log('|-oo-| authBool: ' + authBool)
		if (authBool) {

			// play the selected scene
			currentSceneId = videoId;
//			Scenes.highlightPlaying(currentSceneId);
			// initialize the CVP and set the video something or other
			if (cvpReady) {
				//TURNERPLAYER.play(videoId);
//				player.emptyQueue();
				player.play(firstVid,{'accessToken':accessToken, 'accessTokenType':'Adobe'});
			} else {
/*
				document.getElementById('introSwfContainer').style.display = 'none';
				document.getElementById('adultswim-video-body').style.display = 'block';
*/
				loadCVP();
				waitingVideo = videoId;
			}
		} else {     
			////Utilities.log('You must sign in before accessing full length episodes.  Click the Login button to sign in.')
/*
			$.cookie(CookieJar.cookie_name, $('.nowPlaying').attr('id'), options);
			$.cookie(CookieJar.cookie_name_id, videoId, options);
			$.cookie(CookieJar.cookie_name_page, $('.pageNo').val(), options);
			jQuery.facebox('You must sign in before accessing full length episodes.  Click the Login button to sign in.');
*/
		}
	},
	parseDeepLinkedVideo: function(data){
		// parse the xml to play the video
		var deepLinkedVideoMap = {};
		var orderArray = [];
		
		if ($(data).find('episode').length > 0) {
			$(data).find('episode').each(function(){
				Browse.newvid = Util.storeVideoNode($(this));
				orderArray.push(Browse.newvid.videoId);
				deepLinkedVideoMap[Browse.newvid.videoId] = Browse.newvid;
			});
			
			// keep up with the order the video objects are stored in the array; used for playing through a list
			deepLinkedVideoMap.orderArray = orderArray;
			
			if (deepLinkedVideoMap.orderArray[0] !== undefined && deepLinkedVideoMap.orderArray[0] !== "") {
					//Utilities.log('11111');
				Dramavision.playVideo(deepLinkedVideoMap.orderArray[0], deepLinkedVideoMap);
			} else {
				currentVideoId = "";
				TodaysTop.playFirstVideo();
			}
		}
	},
	Track: function(obj){
		// 'page' tracking; video tracking is handled in /files/tnt_driver_trigger_commands.js
		window.s = window.s ||
		{
			tl: function(){
			},
			t: function(){
			}
		};
		
		var tmp = "";
		for (var name in obj) {
			s[name] = obj[name];
			tmp += " **" + name + ":" + obj[name];
		}
		//////Utilities.log(tmp);
		
		if (obj.pageName == undefined) {
			// track as event
			//s.tl('video event', 'o', 'video event');
			s.t();
		} else {
			// track as page
			s.t();
		}
	}
};
var Slideshow = {
	init: function(){
		////Utilities.log('Slideshow');
			var oSlideshow = $('<div id="slideshow"><span id="deck"></span></div><div id="overlay"><div id="controlPanel"><ul class="clearfix"><li><a href="#" class="ssprev"></a></li><li class="last"><a href="#" class="ssnext"></a></li></ul></div>');
			$('#introSwfContainer').append(oSlideshow);
			Slideshow.addSlides();
	},
	addSlides: function(){
		$.ajax({
			type: "GET",
			url: '/astv/mvpd/services/marketOutput.do?contentId=49046',
			dataType: "xml",
			success: function(xml) {
				//////Utilities.log('b1 success');
				Slideshow.parseXML(xml);
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				//////Utilities.log('b1 addVideos() parse error: ' + XMLHttpRequest + '\n' + textStatus + '\n' + errorThrown);
			},
			complete: function(xml){
				Slideshow.evanHandlerLanding();
//				Slideshow.setupSlideshowLinks();
			}
		}); //close $.ajax
	},
	parseXML: function(xml){
		$(xml).find('item').each(function(i){
			i++;
			$('#deck').append('<div id="slide' + i + '" class="slide" style="background-image:url(' + $(this).attr("image") + ')"><p><span class="showname">' + $(this).attr("title") + '</span> <span class="copy">' + $(this).attr("subtitle") + '</span></p></div>');
			$('#introSwfContainer .last').before('<li id="nav' + i + '"><a class="nav' + i + ' ssnav" href="#"></a></li>');
			////Utilities.log('|-o-| xml: ' + i + ' :: ' + $(this).attr("image"))
		})
	},
	setupSlideshowLinks: function() {
		$("#overlay").click(function(e) {
			var target = $(e.target);
			
			if (target.is('#overlay')) {
				e.stopPropagation();               
				e.preventDefault();
			}
			
			var idStr = $("#controlPanel .on").attr('id');
			var idSplit = idStr.split('nav')
			var id = idSplit[1];
			
			if(e.ctrlKey) {
				window.open($("#deck #slide" + id + " a").attr('href'), "_blank");
			} 
			else {
				window.open($("#deck #slide" + id + " a").attr('href'), "_self");
			}
		})
		
		$("#controlPanel a").click(function(e) {
			var target = $(e.target);
			
			if (target.is('#controlPanel a')) {
				e.stopPropagation();               
				e.preventDefault();
			}
			////Utilities.log(target)
		})
	},
	sniffImgStatus: function(){
		if ($.imagesLoaded()) {
			clearInterval(intSniffStatus);
			//$('#slideshow').pngFix();
			
			var controlPanelWidth = 0;
			
			$('#controlPanel ul li').each(function(i) {
				controlPanelWidth += $(this).innerWidth();
			})
			
			$('#controlPanel').css('width', controlPanelWidth);
			
			$('#deck').width($('#deck').children('div').width() * $('#deck').children('div').length);
			
			
			$('#slideshow #deck .slide p span').each(function(){
				$(this).css('width', $(this).width());
			})
			
			/**** browse ****/
			
			
		}
	},
	overlay: function() {
		$('#slideshow').width('1000px');
		var slideshowLeft = $('#slideshow').position()['left'];
		var slideshowMarginLeft = $('#slideshow').css('margin-left');
		var slideshowTop = $('#slideshow').position()['top'];
		var slideshowMarginTop = $('#slideshow').css('margin-top');
		
		var newSlideshowLeft = parseInt(slideshowLeft) + parseInt(slideshowMarginLeft);
		var newSlideshowTop = parseInt(slideshowTop) + parseInt(slideshowMarginTop);
		
		$("#overlay").css('left', newSlideshowLeft).css('top', newSlideshowTop);
		$("#overlay").show();
	},
	evanHandlerLanding: function(){
		try {
			//////Utilities.log('sliding');
			$('#introSwfContainer').serialScroll({
				target: '#slideshow',
				items: 'div', // Selector to the items ( relative to the matched elements, '#sections' in this case )
				prev: 'a.ssprev',// Selector to the 'prev' button (absolute!, meaning it's relative to the document)
				next: 'a.ssnext',// Selector to the 'next' button (absolute too)
				axis: 'xy',// The default is 'y' scroll on both ways
				navigation: '.ssnav',
				duration: 3000,// Length of the animation (if you scroll 2 axes and use queue, then each axis take half this time)
				force: true, // Force a scroll to the element specified by 'start' (some browsers don't reset on refreshes)
				queue: true,// We scroll on both axes, scroll both at the same time.
				stop: true,// Each click will stop any previous animations of the target. (false by default)
				lock: false, // Ignore events if already animating (true by default)		
				interval: 5000, // It's the number of milliseconds to automatically go to the next
				constant: false
			});
		}catch(e){
			////Utilities.log('evanHandlerLanding err ' + e.name + ' : ' + e.message)
		}
		try {
			intSniffStatus = setInterval("Slideshow.sniffImgStatus()", 500);
			Slideshow.overlay()
		} catch(e){}
		$(window).resize(function(){
			Slideshow.overlay();
		})
	}
}// controller for video info buttons
var VideoButtons = {
	init: function(){
		// activate play info buttons
		$("#sceneSelectionBtn").bind("click", function(e){
			VideoButtons.activate(this, $("#sceneContent"));
			checkExTime();
			e.preventDefault();
		});
		$("#videoButtonAreaClose").bind("click", function(e){
			$("#videoButtonArea").slideUp(200);
			VideoButtons.reset();
			e.preventDefault();
		});
		$("#embedCopyBtn").bind("click", function(e){
			Util.copyToClipboard($("#embedContent textarea"));
			e.preventDefault();
		});
		$("#linkCopyBtn").bind("click", function(e){
			Util.copyToClipboard($("#linkContent textarea"));
			e.preventDefault();
		});
		$("#shareSendBtn").bind("click", function(e){
			if (Validate.validateEmailForm(document.shareVideo)) {
				var inputs = [];
				$(':input', '#shareVideo').each(function(){
					inputs.push(this.name + '=' + escape(this.value));
				});
				
				var pageName = currentVideoObj.heading + ":(" + currentVideoObj.videoId + ")";
				Dramavision.Track({
					eVar2: pageName,
					eVar3: pageName,
					events: "event6"
				});
				
				$.ajax({
					url: Dramavision.SendToFriendUrl,
					data: inputs.join('&'),
					dataType: 'html',
					cache: false,
					error: function(req){
						var msg = (req.readyState !== 4) ? "incomplete request" : req.statusText;
						$("#shareConfirmation").html("There was an error sending your request.<br><br>Please try again later.");
						$("#shareContent").hide();
						$("#shareConfirmation").show();
					},
					success: function(html){
						$("#shareConfirmation").html("Your email has been sent.<br><br>Keep watching videos on TBS.com and share often!");
						$("#shareContent").hide();
						$("#shareConfirmation").show();
					}
				});
			}
			e.preventDefault();
		});
	},
	activate: function(btn, parent){
		// highlight the active button
		VideoButtons.reset();
		$(btn).css("background-color", "#7D4E08");
		$(btn).css("cursor", "default");
		
		/* Clear "friend" fields, but leave "your" fields populated */
		for (var i = 2, l = $("#shareContent input[@type='text']").length; i < l; i++) {
			$("#shareContent input[@type='text']")[i].value = "";
		}
		$("#shareContent textarea")[0].value = "";
		$("#shareConfirmation").hide();
		
		$(parent).show();
		$("#videoButtonArea").fadeIn(200);
		
	},
	deactivate: function(btn, parent){
		// remove button highlight
		$(btn).css("background-color", "#0C0C0C");
		$(btn).css("cursor", "pointer");
		$(parent).hide();
	},
	reset: function(){
		// remove button highlights
		VideoButtons.deactivate($("#sceneSelectionBtn"), $("#sceneContent"));
	}
}

var Scenes = {
	numScenes: 0,
	numPerPage: 4,
	currentPage: 0,
	divPad: 15,
	
	init: function(){
		// activate next/prev buttons
/*
		$("#sceneContent #scenePrevBtn").bind("click", function(e){
			Scenes.slidePrev();
			e.preventDefault();
			return false;
		});
		$("#sceneContent #sceneNextBtn").bind("click", function(e){
			Scenes.slideNext();
			e.preventDefault();
			return false;
		});
*/

	},
	activate: function(){
		// activate play links
		$("#sceneContent .teaserPlay").bind("click", function(e){
			var videoId = $(this).attr('href');
			Dramavision.playScene(videoId.split("?oid=")[1]);
			checkExTime();
			e.preventDefault();
			return false;
		});
	},
	load: function(segments){
	
		//////Utilities.log("in scene load");
		// populate the scenes
		$("#sceneContent #sceneTeasers").empty();
		$("#sceneContent #sceneTeasers").css("margin-left", Scenes.divPad + "px");
		Scenes.numScenes = 0;
		Scenes.currentPage = 0;
		var sceneHtml = "";
		
		for (var i = 0; i < segments.length; i++) {
			var segment = segments[i];
			Scenes.numScenes++;
		}
		
		$("#sceneContent #sceneTeasers").append(sceneHtml);
		
		Scenes.activate();
		Scenes.updateSlideButtons();
		if (Scenes.numScenes > 1) $("#sceneSelectionBtn").show();
		else $("#sceneSelectionBtn").hide();
	},
	slidePrev: function(){
		// slide to the previous page
		Scenes.currentPage--;
		if (Scenes.currentPage < 0) {
			Scenes.currentPage = 0;
		} else {
			Scenes.updateSlideButtons();
		}
		Scenes.slide();
	},
	slideNext: function(){
		// slide to the next page
		var numPages = Math.ceil(Scenes.numScenes / Scenes.numPerPage);
		Scenes.currentPage++;
		if (Scenes.currentPage >= numPages) {
			Scenes.currentPage = (numPages - 1);
		} else {
			Scenes.updateSlideButtons();
		}
		Scenes.slide();
	},
	slide: function(){
		var left = -1 * $("#sceneContent #sceneContainer").width() * Scenes.currentPage + Scenes.divPad;
		// no need to animate if we're already there
		if (left != parseInt($("#sceneContent #sceneTeasers").css("margin-left"))) {
			$("#sceneContent #sceneTeasers").animate({
				'marginLeft': left
			}, 'slow');
		}
	},
	updateSlideButtons: function(){
		// decide whether or not to display the pointer cursor
		var numPages = Math.ceil(Scenes.numScenes / Scenes.numPerPage);
		if (Scenes.currentPage > 0) {
			$("#sceneContent #scenePrevBtn").css("display", "block");
			$("#sceneContent #scenePrevBtn").css("cursor", "pointer");
		} else {
			$("#sceneContent #scenePrevBtn").css("cursor", "default");
			$("#sceneContent #scenePrevBtn").css("display", "none");
		}
		if (numPages > 1 && Scenes.currentPage < (numPages - 1)) {
			$("#sceneContent #sceneNextBtn").css("cursor", "pointer");
			$("#sceneContent #sceneNextBtn").css("display", "block");
		} else {
			$("#sceneContent #sceneNextBtn").css("cursor", "default");
			$("#sceneContent #sceneNextBtn").css("display", "none");
		}
	},
	highlightPlaying: function(videoId){
		// highlight the currently playing scene
		$("#sceneTeasers div").css("background-color", "#7D4E08");
		$("#sceneTeaserItem_" + videoId).css("background-color", "#4380B7");
	},
	empty: function(){
		// remove the scenes and hide the scene selection button
		$("#sceneContent #sceneTeasers").empty();
		$("#sceneSelectionBtn").hide();
	}
}

// controller for the teaser area
var TeaserArea = {
	videoNumber:0,
	init: function(){
		log('{-o-} TeaserArea.init');
		$(".listItem").unbind("click");
		// activate teaser play links
		$(".listItem").bind("click", function(e){
			$('.tn').each(function(){
				$(this).removeClass('nowPlaying').css({
					'background-color': '#fff'
				});
			});
			if( !Browse.bOverrideVid){
				TeaserArea.clickMethod(this);
			}
			e.preventDefault();
			return false;
		});
		
		TeaserArea.highlightPlaying();
		TeaserArea.tnHovers();
	},
	clickMethod: function(obj){
			Browse.videoId = $(obj).addClass('nowPlaying').css({
				'background-color': '#FFF076'
			}).find('img').attr('class').split('*')[0];
			Browse.videoNum = $(obj).attr('id').split('_')[1];
			TeaserArea.bOverrideVid = true;
			//Utilities.log('{-o-} Browse.bOverrideVid ' + Browse.bOverrideVid + ' : ' + TeaserArea.bOverrideVid);
			
			//Utilities.log('33333');
			TeaserArea.loadDescripData(Browse.videoNum);
			checkExTime();
	},
	loadDescripData: function(offset){
		//Utilities.log('|-o-| loadDescripData ' + offset + ' : ' + Browse.collection);
		$.ajax({
			type: "GET",
			url: Dramavision.CollectionUrl + "?limit=1&offset=" + offset + "&id=" + Browse.collection,
			cache: true,
			dataType: "xml",
			success: function(data){
				//Utilities.log("!!!!!! loadDescripData success"+data)
				TeaserArea.parseDescrip(data);
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				//Utilities.log('!!!!!! b1 loadDescripData() parse error: ' + XMLHttpRequest + '\n' + textStatus + '\n' + errorThrown);
//				TeaserArea.doOmni();
				Dramavision.playVideo(Browse.videoId, currentTeaserMap);
			},
			complete: function(data){
			}
		});
	},
	parseDescrip: function(data){
		if ($(data).find('episode').length > 0) {
			$(data).find('episode').each(function(i){
				//alert($(this) + ' :: ' + $(this).children("title").text());
				Browse.newvid = Util.storeVideoNode($(this));
				//Utilities.log('@@@@@ Browse.newvid ' + Browse.newvid);
				currentTeaserMap[Browse.newvid.videoId] = Browse.newvid;
//				TeaserArea.doOmni();
				Dramavision.playVideo(Browse.videoId, currentTeaserMap);
				//orderArray.push(Browse.newvid.videoId);
			});
		}
	},
	doOmni: function(){
		strPageName = $('.nowPlaying .episode-title').text();
		strSubSectionName = $('.nowPlaying .episode-name').text();

		s.server = strSectionName;
		
		if (strSubSectionName != "") {
			s.channel = strSectionName + " : " + strSubSectionName;
			s.pageName = strSectionName + ' : ' + strSubSectionName + ' : ' + strPageName;
		} else {
			s.channel = strSectionName + " : Home";
			s.pageName = strSectionName + ' : ' + strPageName;
		}
		s.t();
	},
	loadData: function(){},
	initRelated: function(){
		// activate teaser play links
		$("#dramavisionTodaysTop .teaserPlay").bind("click", function(e){
			////Utilities.log('{-o-} #dramavisionTodaysTop .teaserPlay ' + videoId)
			var videoId = $(this).attr('href');
			videoAr = videoId.split("?oid=")[1];
			videoId = videoAr.split("*")[0];
			franchiseId = videoAr.split("*")[1];
			Dramavision.playVideo(videoId, relatedTeaserMap);
			Dramavision.loadRelated(videoId, franchiseId);
			checkExTime();
			
			e.preventDefault();
			return false;
		});
		
	},
	loadGrouper: function(grouperId){
		$.ajax({
			type: "GET",
			url: Dramavision.GrouperUrl + "?id=" + grouperId,
			cache: true,
			dataType: "xml",
			success: function(data){
				TeaserArea.loadDeepLinkedVideo(data);
			},
			error: function(){
				Utilities.log("loadGrouper error");
			}
		});
	},
	loadVideos: function(collection){
		Browse.collection = collection;
		//Utilities.log('222a (-oo-) collectionzz: ' + Browse.pageNumber + ' : ' + Browse.collection + ' :: ' + Browse.strCurrCollection);
		if (Browse.strCurrCollection != collection) {
			Browse.strCurrCollection = collection;
		}
		$('.pageNo').val(Browse.pageNumber);
		// get the teaser xml file
		$('#teaserContent').html('<br>loading...');
		//Utilities.log('222b (-oo-) collectionzzz: ' + Browse.pageNumber + ' : ' + collection + ' : ' + currentSectionMap[collection].name + ' :: ' +  +currentSectionMap[collection].expirationDate);
		try {
			$('#teaserAreaTitle').html(currentSectionMap[collection].name);
		} catch (e) {
		
		}
		
		
		try {
			$('#teaserAreaSubTitle').html(currentSectionMap[collection].expirationDate);
		} catch (e) {
		
		}
		
		
		
		//var pageName = "/video/" + currentSectionMap[collection].name;
		//Dramavision.Track({pageName:pageName, prop1:pageName, prop2:""});
		//Utilities.log('\\-o-\\ ' + collection + ' : &offset=' + ((Browse.pageNumber - 1) * (Browse.maxItemsPerPage)) + ' :: ' + (Browse.pageNumber - 1) + ' * ' + (Browse.maxItemsPerPage));
		$.ajax({
			type: "GET",
			url: Dramavision.CollectionUrl + "?limit=" + Browse.MaxVideos + '&offset=' + ((Browse.pageNumber - 1) * Browse.maxItemsPerPage) + "&id=" + collection,
			cache: true,
			dataType: "xml",
			success: function(data){
				////Utilities.log("loadVideos success"+data)
				TeaserArea.populate(data);
			},
			error: function(){
				Utilities.log("loadVideos error");
			}
		});
	},
	loadDeepLinkedVideo: function(data){
		// parse the xml and display the teasers
		grouperTeaserMap = {};
		var videoCount = 0;
		var videoToLaunch = null;
		
		if ($(data).find('episode').length > 0) {
			$(data).find('episode').each(function(){
				Browse.newvid = Util.storeVideoNode($(this));
				grouperTeaserMap[Browse.newvid.videoId] = Browse.newvid;
				videoToLaunch = Browse.newvid.videoId;
				videoCount++;
			});
			
			Dramavision.playVideo(videoToLaunch, grouperTeaserMap);
			
			
		} else {
		}
	},
	populateRelated: function(data){
		// parse the xml and display the teasers
		relatedTeaserMap = {};
		var videoCount = 0;
		var teaserHtml = '<table>';
		
		if ($(data).find('episode').length > 0) {
			$(data).find('episode').each(function(){
				Browse.newvid = Util.storeVideoNode($(this));
				
				relatedTeaserMap[Browse.newvid.videoId] = Browse.newvid;
				
				teaserHtml = teaserHtml.concat('<tr><td width="250" id="teaser_' + Browse.newvid.videoId + '"><table border="0" cellpadding="0" cellspacing="0"><tr><td valign="top"><div class="teaserImage">');
				teaserHtml = teaserHtml.concat('<a href="' + Dramavision.PageUrl + '?oid=' + Browse.newvid.videoId + '*' + Browse.newvid.franchiseId + '" class="teaserPlay" title="play video">');
				teaserHtml = teaserHtml.concat('<img src="' + Browse.newvid.thumb + '" width="96" height="72" border="0" style="border: 1px solid #848588;">');
				teaserHtml = teaserHtml.concat('</a></div></td><td valign="top">');
				teaserHtml = teaserHtml.concat('<div id="teaser_text_' + Browse.newvid.videoId + '" class="teaserText"><div class="teaserTitle">');
				teaserHtml = teaserHtml.concat('<a href="' + Dramavision.PageUrl + '?oid=' + Browse.newvid.videoId + '*' + Browse.newvid.franchiseId + '" class="teaserPlay" title="play video">');
				teaserHtml = teaserHtml.concat('Season ' + Browse.newvid.seasonNumber + ' : Ep. ' + Browse.newvid.episodeNumber + '<br>' + Browse.newvid.episodeTitle + '</a></div>');
				teaserHtml = teaserHtml.concat('<div class="teaserBlurb">' + Browse.newvid.blurb + '</div>');
				teaserHtml = teaserHtml.concat('</div></td></tr></table></td></tr>');
				
				videoCount++;
				
				
			});
			
			teaserHtml = teaserHtml.concat('</table>');
			$('#dramavisionTodaysTop').empty();
			$('#dramavisionTodaysTop').append(teaserHtml);
			
			TeaserArea.initRelated();
			
		} else {
			$('#dramavisionTodaysTop').empty();
			$('#dramavisionTodaysTop').append('<br>There are no related videos for your selection.');
		}
	},
	populate: function(data){
		// parse the xml and display the teasers
		currentTeaserMap = {};
		var videoCount = 0;
		var orderArray = [];
		//		var teaserHtml = '<table style="padding-top: 5px;background:lime;"><tr>';
		
		//Utilities.log('333 !!!!@@@@Browse._nTotalPages ' + Browse._nTotalPages);
		try{
//			if (Browse._nTotalPages == 1) {
				$(data).find('episodes').each(function(){
					Browse._nTotalPages = parseInt(Math.ceil($(this).attr('totalItems') / Browse.maxItemsPerPage));
				});
				$('.pageControls .allDaPages').text(Browse._nTotalPages);
				//Utilities.log('|-o-| ' + parseInt(Math.ceil($(this).attr('totalItems') / Browse.maxItemsPerPage)));
	//		}
		} catch(e){
			//Utilities.log(e.name + ' : ' + e.message);
			Utilities.error(e.name + ' : ' + e.message);
		};
		
		if ($(data).find('episode').length > 0) {
			$('#teaserContent').empty();
			$(data).find('episode').each(function(i){
			
				//Utilities.log('[[-o-]] ' + $(this))
				Browse.newvid = Util.storeVideoNode($(this));
				orderArray.push(Browse.newvid.videoId);
				currentTeaserMap[Browse.newvid.videoId] = Browse.newvid;
				
				
				$('#teaserContent').append('<span class="tn br_false listItem " id="listItem_' + i + '"><div class="thumbnail ' + Dramavision.PageUrl + '"><img src="' + Browse.newvid.thumb + '" width="120" height="90" class="' + Browse.newvid.videoId + '*' + Browse.newvid.franchiseId + '"><div class="sash"></div></div><div class="showtext clearfix"><p class="episode-name">' + Browse.newvid.showTitle + '</p><p class="episode-title">' + Browse.newvid.episodeTitle + '</p><span class="episode-exp">Expires: ' + Browse.newvid.expirationDate + '</span><span class="episode-rating">' + Browse.newvid.rating + '</span><p></p></div></span>');
				videoCount++;
				
			});
			
			
			// keep up with the order the video objects are stored in the array; used for playing through a list
			currentTeaserMap.orderArray = orderArray;
			
			Browse.bOverrideVid = false;
			TeaserArea.init();
					$('#all-adultswim-videos-container').height(parseInt($('#all-adultswim-videos').height() + 60));

		//Utilities.log('{-o-} all-adultswim-videos height: ' + $('#all-adultswim-videos').height() + ' :: ' + $('.pagBot').height() + ' : ' + $('.pagBot').css('top'));

			if (deepLinkedCategory !== "" && currentVideoId === "" && waitingVideo === "") {
				//////Utilities.log("in playVideo");
				// if we just loaded a deeplinked category, play the first video if there isn't a deeplinked video
				deepLinkedCategory = "";
				Dramavision.playVideo(currentTeaserMap.orderArray[0], currentTeaserMap);
			}
			
		} else {
			TeaserArea.error();
		}
	},
	resize: function(){
		$("#teaserArea").css("height", $("#sectionNavArea").height());
	},
	error: function(){
		// handle error retrieving videos or an empty video list
		$('#teaserContent').empty();
		$('#teaserContent').html('<br>There are no videos for your selection.');
	},
	highlightPlaying: function(){
		// highlight the currently playing video
		////Utilities.log('|-o-| currentVideoId ' + currentVideoId)
		$('#listItem').removeClass("teaserActive");
		$('#listItem_' + currentVideoId).addClass("teaserActive");
	},
	tnHovers: function(){
		$('.tn').corner("round 6px").hover(function(){
			Dramavision.strBgColor = '#FFF076';
			$(this).css({
				'background': Dramavision.strBgColor
			});
			////Utilities.log('wax on ' + $(this).attr('class'));
		}, function(){
			($(this).hasClass('nowPlaying')) ? Dramavision.strBgColor = '#FFF076' : Dramavision.strBgColor = '#fff';
			$(this).css({
				'background': Dramavision.strBgColor
			});
			////Utilities.log('wax off ' + $(this).attr('class'));
		});
	}
}

// controller for main horizontal nav
var MainNav = {
	init: function(){
		// highlight the selected main nav item now
		MainNav.highlightSelected();
		
		// set the rollover effect for each nav item
		$(".dramavisionNavItem").hover(function(){
			$(this).addClass("dramavisionNavItemHover");
		}, function(){
			if (selectedCollection != $(this).attr('name')) {
				$(this).removeClass("dramavisionNavItemHover");
			}
		});
		
		// activate the click action for each nav item
		$(".dramavisionNavItem").click(function(e){
		
			selectedCollection = $(this).attr('name');
			SectionNav.load(selectedCollection);
			MainNav.highlightSelected();
			//	TeaserArea.loadVideos(firstcollectionid);////Utilities.log('test');
			checkExTime();
			e.preventDefault();
			return false;
		});
	},
	highlightSelected: function(){
		// highlight the selected nav item, and remove the highlight from the rest
		$(".dramavisionNavItem").each(function(){
			if (selectedCollection != $(this).attr('name')) {
				$(this).removeClass("dramavisionNavItemHover");
			} else {
				$(this).addClass("dramavisionNavItemHover");
			}
		});
	},
	removeHighlight: function(){
		selectedCollection = '';
		MainNav.highlightSelected();
	},
	findSection: function(categoryId, myxml){
		// traverse through the xml file to find the parent section of a category,
		// and decide if this category has videos or not; if not, find a child who does
		var newSection = "";
		var foundSection = "";
		$(myxml).find('collection').each(function(){
			newSection = $(this).children('name').text();
			if ($(this).attr('id') == categoryId) {
				foundSection = newSection;
				if ($(this).children('subcollection').length > 0) {
					var subcat = $(this).children('subcollection');
					if ($(subcat).children('subcollection').length > 0) {
						var subsubcat = $(this).children('subcollection');
						if ($(subsubcat).children('subcollection').length > 0) {
							deepLinkedCategory = $(subsubcat).children('subcollection').attr('id');
						} else {
							deepLinkedCategory = $(subcat).children('subcollection').attr('id');
						}
					} else {
						deepLinkedCategory = $(this).children('subcollection').attr('id');
					}
				}
				return;
			} else {
				if ($(this).children('subcollection').length > 0) {
					$(this).children('subcollection').each(function(){
						if ($(this).attr('id') == categoryId) {
							foundSection = newSection;
							if ($(this).children('subcollection').length > 0) {
								var subcat = $(this).children('subcollection');
								if ($(subcat).children('subcollection').length > 0) {
									deepLinkedCategory = $(subcat).children('subcollection').attr('id');
								} else {
									deepLinkedCategory = $(this).children('subcollection').attr('id');
								}
							}
							return;
						} else {
							if ($(this).children('subcollection').length > 0) {
								$(this).children('subcollection').each(function(){
									if ($(this).attr('id') == categoryId) {
										foundSection = newSection;
										if ($(this).children('subcollection').length > 0) {
											deepLinkedCategory = $(this).children('subcollection').attr('id');
										}
										return;
									} else {
										if ($(this).children('subcollection').length > 0) {
											$(this).children('subcollection').each(function(){
												if ($(this).attr('id') == categoryId) {
													foundSection = newSection;
													return;
												}
											});
										}
									}
								});
							}
						}
					});
				}
			}
		});
		return foundSection;
	}
}

// controller for the section navigation
var SectionNav = {
	init: function(){
		// activate the div clicks
		$(".sectionNavCell").click(function(e){
			COOKIE_VAL_page = 1;
			COOKIE_VAL_collection = $(this).attr('id');
			$.cookie(CookieJar.cookie_name_collection, COOKIE_VAL_collection,options);
			Browse.pageNumber = 1;
//			Browse._nTotalPages = 1;
//			$('.pageNo').val(1);
//			$('.pageNo').text(1);
			//Utilities.log('333 {-o-} .sectionNavCell id ' + $(this).attr('id'));
			SectionNav.toggle(this);
			$('h2.browse').html($(this).text());
			if ($(this).next(".sectionNavSubGroup").length == 0) {
				// get the collection id from the div name attribute
				TeaserArea.loadVideos(COOKIE_VAL_collection);
			}
			checkExTime();
			e.preventDefault();
			return false;
		});
		
		$(".sectionNavCellActive").click(function(e){
			SectionNav.toggle(this);
			e.preventDefault();
			return false;
		});
		
		$(".sectionNavSubCell").click(function(e){
			SectionNav.toggle(this);
			if ($(this).next(".sectionNavSubGroup").length == 0) {
				// get the collection id from the div name attribute
				TeaserArea.loadVideos($(this).attr('id'));
			}
			e.preventDefault();
			return false;
		});
		
		$(".sectionNavSubSubCell").click(function(e){
			SectionNav.resetSubSubNavCells();
			$(this).removeClass("sectionNavSubSubCell").addClass("sectionNavSubSubCellActive");
			
			// get the collection id from the div name attribute
			TeaserArea.loadVideos($(this).attr('id'));
			e.preventDefault();
			return false;
		});
		
		// resize the teaser area to match the height of the section nav
		TeaserArea.resize();
	},
	toggle: function(div){
		// open or close the divs
		if ($(div).hasClass("sectionNavCell")) {
			SectionNav.resetNavCells();
			$(div).next(".sectionNavSubGroup").show("slow", TeaserArea.resize);
			$(div).removeClass("sectionNavCell").addClass("sectionNavCellActive");
		} else if ($(div).hasClass("sectionNavSubCell")) {
			SectionNav.resetSubNavCells();
			$(div).next(".sectionNavSubGroup").show("slow", TeaserArea.resize);
			$(div).removeClass("sectionNavSubCell").addClass("sectionNavSubCellActive");
		}
		/* don't close it
		 else if ($(div).hasClass("sectionNavCellActive")) {
		 $(div).next(".sectionNavSubGroup").hide("slow");
		 $(div).removeClass("sectionNavCellActive").addClass("sectionNavCell");
		 }
		 */
	},
	resetNavCells: function(){
		// close all the divs
		$(".sectionNavCellActive").each(function(){
			$(this).next(".sectionNavSubGroup").hide("slow", TeaserArea.resize);
			$(this).removeClass("sectionNavCellActive").addClass("sectionNavCell");
		});
		SectionNav.resetSubNavCells();
	},
	resetSubNavCells: function(){
		// close all the subnav divs
		$(".sectionNavSubCellActive").each(function(){
			$(this).next(".sectionNavSubGroup").hide("slow", TeaserArea.resize);
			$(this).removeClass("sectionNavSubCellActive").addClass("sectionNavSubCell");
		});
		SectionNav.resetSubSubNavCells();
	},
	resetSubSubNavCells: function(){
		// close all the subnav divs
		$(".sectionNavSubSubCellActive").each(function(){
			$(this).removeClass("sectionNavSubSubCellActive").addClass("sectionNavSubSubCell");
		});
	},
	load: function(section){
		// load the selected collection
		$("#sectionNavArea").html("loading....");
		if (navXml === "") {
			// if nav is still loading, store the section
			waitingSection = section;
			
			// should only happen when a user clicks so we can remove the deep linked category
			deepLinkedCategory = "";
		} else {
			// traverse xml to find section belonging to deepLinkedCategory; if none remove deeplinked status
			if (deepLinkedCategory !== "") {
				var foundSelectedSection = MainNav.findSection(deepLinkedCategory, navXml);
				
				// once we find the section set it as selectedSection and run main nav highlight; also set section
				if (foundSelectedSection !== "") {
					selectedCollection = foundSelectedSection.toUpperCase();
					section = foundSelectedSection;
					MainNav.highlightSelected();
				} else {
					// if we don't find it set deepLinkedCategory = "";
					deepLinkedCategory = "";
					
					// didn't find the deeplinked category so play the default video from today's top
					TodaysTop.playFirstVideo();
				}
			}
			
			// find the collection in the xml create the nav display
			var firstcollectionid = "";
			currentSectionMap = {};
			
			$(navXml).find('collection').each(function(){
				var mycollection = $(this).children('name').text();
				if (mycollection.toUpperCase() == section.toUpperCase()) {
					var mycollectionid = $(this).attr('id');
					firstcollectionid = mycollectionid;
					
					$("#sectionNavArea").empty();
					if ($(this).children('subcollection').length < 1) {
						var newsection = {};
						newsection.name = $(this).children('title').text();
						newsection.expirationDate = $(this).children('expirationDate').text();
						currentSectionMap[$(this).attr('id')] = newsection;
						
						TeaserArea.loadVideos(COOKIE_VAL_collection);//mycollectionid;
						
					} else {
					
						var navhtml = '<dt id="sectionNavTitle">' + mycollection + '</dt>';
						var numcollections = 0;
						
						$(this).children('subcollection').each(function(){
							if (numcollections === 0) {
								firstcollectionid = $(this).attr('id');
								
							}
							var newsection = {};
							newsection.name = $(this).children('title').text();
							newsection.expirationDate = $(this).children('expirationDate').text();
							currentSectionMap[$(this).attr('id')] = newsection;
							var mysubcollectionname = $(this).children('title').text();
							navhtml = navhtml.concat('<dd class="sectionNavCell" id="' + $(this).attr('id') + '"><a href="javascript:void();">' + $(this).children('name').text() + '</a></dd>');
							if ($(this).children('subcollection').length > 0) {
								var subgroup = '<dl class="sectionNavSubGroup">';
								var numsubcollections = 0;
								$(this).children('subcollection').each(function(){
									if (numcollections === 0 && numsubcollections === 0) {
										firstcollectionid = $(this).attr('id');
										
									}
									subgroup = subgroup.concat('<dd class="sectionNavSubCell" id="' + $(this).attr('id') + '"><a href="javascript:void();">' + $(this).children('name').text() + '</a></dd>');
									var newsection = {};
									newsection.name = mysubcollectionname + ": " + $(this).children('name').text();
									newsection.expirationDate = $(this).children('expirationDate').text();
									currentSectionMap[$(this).attr('id')] = newsection;
									var mysubsubcollectionname = $(this).children('name').text();
									
									if ($(this).children('subcollection').length > 0) {
										var subsubgroup = '<div class="sectionNavSubGroup">';
										var numsubsubcollections = 0;
										$(this).children('subcollection').each(function(){
											if (numcollections === 0 && numsubcollections === 0 && numsubsubcollections === 0) {
												firstcollectionid = $(this).attr('id');
												
											}
											subsubgroup = subsubgroup.concat('<div class="sectionNavSubSubCell" id="' + $(this).attr('id') + '"><b>' + $(this).children('name').text() + '</b></div>');
											var newsection = {};
											newsection.name = mysubcollectionname + ": " + mysubsubcollectionname + ": " + $(this).children('name').text();
											newsection.expirationDate = $(this).children('expirationDate').text();
											currentSectionMap[$(this).attr('id')] = newsection;
											numsubsubcollections++;
											
										});
										subsubgroup = subsubgroup.concat('</div>');
										subgroup = subgroup.concat(subsubgroup);
									}
									numsubcollections++;
								});
								subgroup = subgroup.concat('</div>');
								navhtml = navhtml.concat(subgroup);
							}
							numcollections++;
						});
//						navhtml = navhtml.concat('</dl>');
						$("#sectionNavArea").append(navhtml);
						
						//////Utilities.log("firstcollectionid="+firstcollectionid)
						
//						TeaserArea.loadVideos(firstcollectionid); //added per defect 195
						TeaserArea.loadVideos(COOKIE_VAL_collection);

					}
				}
			});
			SectionNav.init();
			
			
			
			
			// if currentTeaserMap is empty, load the deeplinked category or the first collection with videos
			if (Util.isEmptyObject(currentTeaserMap)) {
				if (deepLinkedCategory !== "") {
					// load the videos for the deeplinked category
					TeaserArea.loadVideos(COOKIE_VAL_collection);//deepLinkedCategory

					
					// open up the category in the left nav
					var div = $("#" + deepLinkedCategory);
					if ($(div).hasClass("sectionNavCell")) {
						$(div).removeClass("sectionNavCell").addClass("sectionNavCellActive");
						
					} else if ($(div).hasClass("sectionNavSubCell")) {
						$(div).parent(".sectionNavSubGroup").show("slow", TeaserArea.resize);
						$(div).parent(".sectionNavSubGroup").prev(".sectionNavCell").removeClass("sectionNavCell").addClass("sectionNavCellActive");
						$(div).removeClass("sectionNavSubCell").addClass("sectionNavSubCellActive");
						
					} else if ($(div).hasClass("sectionNavSubSubCell")) {
						$(div).parent(".sectionNavSubGroup").prev(".sectionNavSubCell").parent(".sectionNavSubGroup").show("slow", TeaserArea.resize);
						$(div).parent(".sectionNavSubGroup").prev(".sectionNavSubCell").parent(".sectionNavSubGroup").prev(".sectionNavCell").removeClass("sectionNavCell").addClass("sectionNavCellActive");
						$(div).parent(".sectionNavSubGroup").show("slow", TeaserArea.resize);
						$(div).parent(".sectionNavSubGroup").prev(".sectionNavSubCell").removeClass("sectionNavSubCell").addClass("sectionNavSubCellActive");
						$(div).removeClass("sectionNavSubSubCell").addClass("sectionNavSubSubCellActive");
					}
				} else {
					Utilities.log('!! ' + COOKIE_VAL_collection + ' : ' + firstcollectionid);
					TeaserArea.loadVideos(COOKIE_VAL_collection);//firstcollectionid
					
				}
			}
		}
	}
}

// controller for playlist area
var PlaylistArea = {
	init: function(){
	
		// activate playlist tabs
		$("#dramavisionTodaysTopBtn").bind("click", function(e){
			PlaylistArea.togglePlaylist('todaysTop');
			e.preventDefault();
		});
		
	},
	togglePlaylist: function(playlistType){
	}
}

// controller for Today's Top Videos
var TodaysTop = {
	init: function(){
		// activate teaser play links
		$("#dramavisionTodaysTop .teaserPlay").bind("click", function(e){
			var videoId = $(this).attr('href');
			Dramavision.playVideo(videoId.split("?oid=")[1], currentTodaysTopMap);
			checkExTime();
			e.preventDefault();
			return false;
		});
	},
	loadVideos: function(){
		// get the xml for today's top videos
		$.ajax({
			type: "GET",
			url: Dramavision.CollectionUrl + "?limit=" + Browse.MaxVideos + "&id=" + Dramavision.TodaysTopId,
			cache: true,
			dataType: "xml",
			success: function(data){
				TodaysTop.populate(data);
			},
			error: function(){
				Utilities.log("loadVideos2 error");
			}
		});
	},
	populate: function(data){
		// parse the xml and display the today's top video links
		currentTodaysTopMap = {};
		var orderArray = [];
		var videoCount = 0;
		var teaserHtml = '';
		
		$(data).find('episode').each(function(){
			Browse.newvid = Util.storeVideoNode($(this));
			orderArray.push(Browse.newvid.videoId);
			currentTodaysTopMap[Browse.newvid.videoId] = Browse.newvid;
			
			if (videoCount % 2 === 0) {
				teaserHtml = teaserHtml.concat('<div class="dramavisionPlayListItem" id="' + Browse.newvid.videoId + '">');
			} else {
				teaserHtml = teaserHtml.concat('<div class="dramavisionPlayListItemAlt" id="' + Browse.newvid.videoId + '">');
			}
			teaserHtml = teaserHtml.concat('<a href="' + Dramavision.PageUrl + '?oid=' + Browse.newvid.videoId + '" class="teaserPlay" title="play video">');
			teaserHtml = teaserHtml.concat(Browse.newvid.heading + '</a></div>');
			
			videoCount++;
		});
		
		$('#dramavisionTodaysTop').empty();
		$('#dramavisionTodaysTop').append(teaserHtml);
		
		// keep up with the order the video objects are stored in the array; used for playing through a list
		currentTodaysTopMap.orderArray = orderArray;
		
		TodaysTop.playFirstVideo();
		TodaysTop.init();
	},
	playFirstVideo: function(){
		var firstVideo = $('#dramavisionTodaysTop').children('.dramavisionPlayListItem').children('a').attr('href');
		if (currentVideoId === "" && waitingVideo === "" && deepLinkedCategory === "" && firstVideo != undefined) {
			Dramavision.playVideo(firstVideo.split("?oid=")[1], currentTodaysTopMap);
		}
	}
}

// Add trim test for user's search entry
function leftTrim(sString){
	while (sString.substring(0, 1) == ' ') {
		sString = sString.substring(1, sString.length);
	}
	return sString;
}

// controller for search
var Search = {
	init: function(){
		// set the action for the submit button
		$("#searchForm").bind("submit", function(e){
			Search.submit();
			e.preventDefault();
		}).bind("keypress", function(e){
			var key = e.charCode ? e.carChode : e.keyCode ? e.keyCode : 0;
			if (key === 13) {
				Search.submit();
				e.preventDefault();
			}
		});
	},
	submit: function(){
		// send and load the search request - add test for empty string and </ and ;
		if (document.searchForm.query.value == '<c:out value="${defaultSearchValue}"/>' ||
		leftTrim(document.searchForm.query.value).length == 0 ||
		document.searchForm.query.value.indexOf("</") >= 0 ||
		document.searchForm.query.value.indexOf(";") >= 0) {
			////Utilities.log('Please insert a search keyword');
		} else {
			$("#sectionNavArea").empty();
			$('#teaserContent').html('<br>loading...');
			$('#teaserAreaTitle').html('Search: ' + document.searchForm.query.value);
			$('#teaserAreaSubTitle').empty();
			MainNav.removeHighlight();
			
			var inputs = [];
			$(':input', '#searchForm').each(function(){
				inputs.push(this.name + '=' + escape(this.value));
			});
			
			$.ajax({
				type: "GET",
				url: Dramavision.SearchUrl,
				data: inputs.join('&'),
				cache: true,
				dataType: "xml",
				error: function(req){
					TeaserArea.error();
				},
				success: function(data){
					var pageName = document.searchForm.query.value;
					var omnitureObj = {
						prop14: pageName,
						prop15: "Dramavision",
						prop16: "Dramavision:Search",
						eVar14: pageName,
						eVar15: "Dramavision",
						eVar16: "Dramavision:Search"
					};
					if ($(data).find('episodes').attr("totalItems") === "0") {
						omnitureObj.prop13 = pageName;
					}
					Dramavision.Track(omnitureObj);
					
					TeaserArea.populate(data);
				},
				error: function(){
					Utilities.log("submit error")
				}
			});
		}
	}
}

// cookie functions
/*
CookieJar.cookie_namekieJar = {
	getCookie: function(name){
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		
		for (var i = 0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ') {
				c = c.substring(1, c.length);
			}
			if (c.indexOf(nameEQ) == 0) {
				return c.substring(nameEQ.length, c.length);
			}
		}
		return null;
	},
	setCookie: function(name, value, days){
		if (days) {
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			var expires = "; expires=" + date.toGMTString();
		} else {
			var expires = "";
		}
		document.cookie = name + "=" + value + expires + "; path=/";
	}
}
*/
// basic utility functions
var Util = {
	formatDate: function(str){
		return $.format.date(str, "MM/dd/YY")
	},
	storeVideoNode: function(node){
		Browse.newvid = {};
		Browse.newvid.videoId = $(node).attr("id");
		Browse.newvid.showTitle = $(node).children("seriesName").text();
		Browse.newvid.episodeTitle = $(node).children("episodeTitle").text();
		Browse.newvid.seasonNumber = $(node).children("seasonNumber").text();
		Browse.newvid.episodeNumber = $(node).children("episodeNumber").text();
		Browse.newvid.franchiseId = $(node).children("franchiseId").text();
		Browse.newvid.collectionId = $(node).attr("collectionId");
		Browse.newvid.thumb = $(node).children("thumbnailUrl").text();
		Browse.newvid.heading = $(node).children("title").text();
		Browse.newvid.blurb = $(node).children("shortBlurb").text();
		Browse.newvid.description = $(node).children("description").text();
		Browse.newvid.expirationDate = Util.formatDate($(node).children("expirationDate").text());
		Browse.newvid.embeddable = $(node).children("embeddable").text();
		Browse.newvid.mavenExternalId = $(node).children("mavenExternalId").text();
		Browse.newvid.franchiseName = $(node).children("franchiseName").text();
		Browse.newvid.playlistId = $(node).children("mavenPlaylistId").text();
		Browse.newvid.rating = $(node).children("tvRatingCode").text();
		Browse.newvid.tveMode = $(node).children("tveMode").text();
		
		var segments = [];
		$(node).find('segment').each(function(){
			var segment = {};
			segment.videoId = $(this).attr("id");
			segment.thumb = $(this).children("thumbnailUrl").text();
			segment.heading = $(this).children("title").text();
			segment.blurb = $(this).children("shortBlurb").text();
			segment.description = $(this).children("description").text();
			segment.expirationDate = Util.formatDate($(this).children("expirationDate").text());
			segments.push(segment);
		});
		Browse.newvid.segments = segments;
		
		return Browse.newvid;
	},
	isEmptyObject: function(obj){
		// check if an object is empty
		for (var i in obj) {
			return false;
		}
		return true;
	},
	copyToClipboard: function(textarea){
		// copy text from a textarea to the clipboard
		$(textarea).css("background-color", "#0A3256");
		window.setTimeout(function(){
			$(textarea).css("background-color", "#FFF");
		}, 60);
		
		var txt = $(textarea)[0].value;
		if (txt.createTextRange) {
			range = txt.createTextRange();
			if (range && (BodyLoaded == 1)) {
				range.execCommand("Copy");
			}
		} else {
			$('#clipboardProxy').html('<embed id=clipboardFlash" src="<c:out value="${imagePath}" />/flash/clipboardProxy.swf" FlashVars="clipboard=' + encodeURIComponent(txt) + '" width="0" height="0" type="application/x-shockwave-flash"></embed>');
		}
	}
}

// form validation functions
var Validate = {
	isEmpty: function(fieldValue){
		if ((fieldValue.length == 0) || (fieldValue == null)) {
			return true;
		} else {
			return false;
		}
	},
	isEmptyRadio: function(field){
		for (i = 0; i < field.length; i++) {
			if (field[i].checked) {
				return false;
			}
		}
		return true;
	},
	isNumeric: function(fieldValue){
		var ValidChars = "0123456789.";
		var IsNumber = true;
		var Char;
		
		for (i = 0; i < fieldValue.length && IsNumber == true; i++) {
			Char = fieldValue.charAt(i);
			if (ValidChars.indexOf(Char) == -1) {
				IsNumber = false;
			}
		}
		return IsNumber;
	},
	isEmail: function(fieldvalue){
		var i = 1;
		var sLength = fieldvalue.length;
		
		// look for @
		while ((i < sLength) && (fieldvalue.charAt(i) != "@")) {
			i++
		}
		
		if ((i >= sLength) || (fieldvalue.charAt(i) != "@")) {
			return false;
		} else {
			i += 2;
		}
		
		// look for .
		while ((i < sLength) && (fieldvalue.charAt(i) != ".")) {
			i++
		}
		
		// there must be at least one character after the .
		if ((i >= sLength - 1) || (fieldvalue.charAt(i) != ".")) {
			return false;
		} else {
			return true;
		}
	},
	validateEmailForm: function(form){
		var valid = true;
		var msg = "Please correct the following information - \n\n";
		
		if (Validate.isEmpty(form.fp_sender.value)) {
			msg += "- Your name is required \n";
			valid = false;
		}
		if (Validate.isEmpty(form.fp_sender_email.value)) {
			msg += "- Your email is required \n";
			valid = false;
		} else if (!Validate.isEmail(form.fp_sender_email.value)) {
			msg += "- Your email is not a valid email address \n";
			valid = false;
		}
		if (Validate.isEmpty(form.fp_friend.value)) {
			msg += "- Friend's name is required \n";
			valid = false;
		}
		if (Validate.isEmpty(form.fp_friend_email.value)) {
			msg += "- Friend's email is required \n";
			valid = false;
		} else if (!Validate.isEmail(form.fp_friend_email.value)) {
			msg += "- Friend's email is not a valid email address \n";
			valid = false;
		}
		
		if (!valid) {
			////Utilities.log(msg);
		}
		return valid;
	}
};
BrowseButtons = {
	setupClicks: function(){
	// page nav
		//next page
			$('.navNext').click(function(){
				//Utilities.log('NEXT! ' + (Browse.pageNumber<= Browse._nTotalPages) + ' :: ' + Browse.pageNumber + ' : ' + Browse._nTotalPages);
				if (Browse.pageNumber < Browse._nTotalPages) {
					Browse.pageNumber++;
					Browse.strDirection = 'next';
					Browse.bOverrideBlur = false;
					Browse.bOverrideVid = true;
					//Utilities.log('_BROWSE_NEXT CLICKED');
					//Browse.addVideos();
					TeaserArea.loadVideos(Browse.strCurrCollection);
					Browse.bOverrideVid;
					//Browse.updatePage();
				}
			});
		// prev page
			$('.navPrev').click(function(){
				if (Browse.pageNumber > 1) {
					Browse.pageNumber--;
					Browse.strDirection = 'prev';
					Browse.bOverrideBlur = false;
					Browse.bOverrideVid = true;
					//Utilities.log('_BROWSE_PREV CLICKED');
					//Browse.addVideos();
					TeaserArea.loadVideos(Browse.strCurrCollection);
					Browse.bOverrideVid
					//Browse.updatePage();
				}
			});
			
		//page nav actions (focus/blur/keypress)
		$('.pageNo').focus(function(){
			Browse._objVidz['_ncount'] = 0;
			Browse.bOverrideBlur = false;
			Browse.bOverrideVid = true;
			Browse.strPagination = $(this).val();
			$('.pageNo').val('');
		});
		$('.pageNo').blur(function(){
				//////Utilities.log('Blurr: ' + Browse.bOverrideBlur + ' : ' + $(this).val());
				Browse._nTotalPages = $('.pagTop .allDaPages').text();
				Browse.bOverrideVid = true;
				if (!Browse.bOverrideBlur) {
					Browse._objVidz['_ncount'] = 0;
					Browse.updatePage($(this).val());
				}
		});
		$('.pageNo').keypress(function (e) {
			switch(e.which){
				case 48: // 0
				case 49: // 1
				case 50: // 2
				case 51: // 3
				case 52: // 4
				case 53: // 5
				case 54: // 6
				case 55: // 7
				case 56: // 8
				case 57: // 9
					return true;
					break;
				case 0:  //nav
				case 8:  // backspace
					return true;
					break;
				case 13:  // enter
					//////Utilities.log('case 13: ' + $(this).val());
					Browse.bOverrideBlur = true;
					Browse.bOverrideVid = true;
					Browse.updatePage($(this).val());
					$('.pageNo').blur();
					return false;
					break;
				default:
					return false;
					break;
			}
		});
	}
};
var Utilities = {
	getCookieNames: function(){
		return CookieJar;
	},
	cookieMonster: function(strCookies){

		switch(strCookies){
			case null:
			case undefined:
			case '':
				var CookieJar = Utilities.getCookieNames();
				break;
			default:
				var strDelimiter = strCookies.match(/[\|:\.,#-]/);
				var CookieJar = strCookies.split(strDelimiter);
				break;
		}

		var cookie = '';
		var cookie_action = null;
		for (var c in CookieJar){
			cookie = CookieJar[c].replace(/ /g,'');
			switch(cookie){
				case 'TVEpage':
					
					$.cookie(cookie,1,options)
					break;
				case 'TVEcollection':
					$.cookie(cookie,nAllEpisodesCollectionId,options)
					break;
				default:
					$.cookie(cookie,null,options)
					break;
			}
		}
	},
	log: function(str){
		try{
			console.log(str)
		} catch (e){
		}
	},
	debug: function(str){
		try{
			console.debug(str)
		} catch (e){}
	},
	trace: function(str){
		try{
			console.trace(str)
		} catch (e){}
	},
	info: function(str){
		try{
			console.info(str)
		} catch (e){}
	},
	warn: function(str){
		try{
			console.warn(str)
		} catch (e){}
	},
	error: function(str){
		try{
			console.error(str)
		} catch (e){}
	}
};
jQuery.imagesLoaded = function() {
	var bImgLoaded = true;
		$('.vidImg').each(function(){
			if ($(this).complete == false) {
				bImgLoaded = false;
			}
		})
	return bImgLoaded;
	}

