/**
 * @fileoverview These are the TBS effects. They are dependent on core.js
 * @version 1.0
 * @requires core.js
 * @author Richard Herrera, David Zuch, Michael Bester, Carlos Porto
 */

/**
 * @author Richard Herrera
 * @namespace TBS
 *
 * The TBS Namespace. Anything that might need editing by TBS belongs here.
 * No jQuery API should be present here. Treat this as a bridge to jQuery.
 */
var TBS = {

	/* This is the trigger parameter
	When VideoIsPlaying = true, next video does not trigger */
	VideoIsPlaying : false,

	/* Default videos per page (when pagination is in play)
	Note: This parameter MUST match server side's parameter */
	VideosPerPage : 10,

	/* In case this directory is ever changed, you can do it globally here */
	Directory : "",

	/* When returning HTML (via /video/featured/), we eval the returning JSON
	And assign the object to this parameter */
	JSON_ID : "TBS_Video",

	/* The Content Hierarchy Object (CHO) */
	CHO : "/exclude/genericContainer/0,,123065,00.html",

	/* Featured Video URL */
	FeaturedVideo : "/exclude/videoplayer/2007/featureVideo.jsp",

	/* The URL to use when pulling data for "My Playlist" */
	PlaylistInfo : "/exclude/videoplayer/2007/playlistinfo.jsp?cid=",

	/* The URL to use when pulling data for "Search" */
	SearchInfo : "/video/search.jsp",

	/* The TBS "Panic" spreadsheet image location */
	FakeSpreadSheet : "http://i.cdn.turner.com/v5cache/TBS/video/img/tmp/fake_spreadsheet.gif",

	/* The URL to use to submit your playlist to */
	SharePlaylistSubmission : "/processors/video/sendplaylist.jsp",

	/* The URL to use to submit your video to */
	ShareVideoSubmission : "/processors/veryfunnyads/sendtoafriend.jsp",

	/* Makes current video info available to Omniture code anywhere */
	CurrentVideo : "",

	/* The "Money" function. Used to play videos */
	Play : function(e) {
		/* If a video is playing, or if no parameters are passed,
		there's no need to go further. */
		if (this.VideoIsPlaying || !e) {
			return;
		}

		/* We've gone this far, thus a video is playing */
		this.VideoIsPlaying = true;

		/* Set a variable to store */
		var currentVideo, currentVideoPos;

		/* If a function does not declare TBS.Video,
		it's probably stored in the featured html.
		Let's set it as such. */
		this.Video = this.Video || [window[TBS.JSON_ID]];

		/* If parameter is an href */
		if (typeof e == "string") {

			/* Loop through the Video object */
			for (var i = 0, j = this.Video[0].videos.length; i < j; i++) {

				/* If this object's url is the same as our parameter,
				Set variable "currentVideo" to this. */
				if (unescape(this.Video[0].videos[i].url) == unescape(e)) {
					currentVideo = this.Video[0].videos[i];
					TBS.CurrentVideo = currentVideo;
					currentVideoPos = i;
					/* No need to loop further, let's break out. */
					break;
				}
			}

		/* If parameter is an array */
		} else if (e[0]) {

			/* Assign the array to the Video object */
			this.Video = e;

			/* Because the parameter is an array,
			We'll play the first video in that array by default
			Set variable "currentVideo" to first video. */
			currentVideo = this.Video[0];
			currentVideoPos = 0;

		/* If parameter is an object */
		} else {

			/* Assign the object to an array */
			this.Video = [e];

			/* Now assign the array to the Video object
			We'll play the first video in that array by default
			Set variable "currentVideo" to first video. */
			currentVideo = this.Video[0];
			currentVideoPos = 0;
		}

		/* If either this.Video or currentVideo is undefined, return */
		if (!this.Video || !currentVideo) {
			return;
		}

		/* Make sure variable "currentVideo" is set correctly */
		if(currentVideo.videos) {
			currentVideo = currentVideo.videos[0];
			currentVideoPos = 0;
		}

		TBS.CurrentVideo = currentVideo;
		TBS.CurrentVideoPos = currentVideoPos || 0;

		if(!currentVideo.isscene || currentVideo.isscene < 2) {
			Tabs.prototype.populate(currentVideo);
		}

		if(!currentVideo.isscene) {
			currentVideo = this.Scenes(currentVideo);
		} else {
			this.DoPlay(currentVideo);
		}
	},

	DoPlay : function(currentVideo) {

		/* Check for active state */
		TBS.Current();

		/* We're calling a new video, so let's empty out div #xmp */
		var xmp = document.getElementById("xmp");

		/* While #xmp has child nodes, nix the last child */
		while (xmp.hasChildNodes()) {
			xmp.removeChild(xmp.lastChild);
		}

		/* Creating the necessary elements */
		var franchise = document.createElement("h2"),
		    title = document.createElement("h3"),
		    next = document.createElement("h3");

		/* Append franchise info to h2 */
		franchise.appendChild(document.createTextNode(currentVideo.franchise));

		/* Append season, episode, title info to h3.title */
		title.className = "title";
		title.appendChild(document.createTextNode(""));
		if (currentVideo.seasonnum) {
			title.firstChild.nodeValue += "season " + currentVideo.seasonnum + " - ";
		}
		if (currentVideo.episodenum) {
			title.firstChild.nodeValue += "episode " + currentVideo.episodenum + ": ";
		}
		if (currentVideo.episodetitle) {
			title.firstChild.nodeValue += currentVideo.episodetitle;
		}

		/* Append next nextairing info to h3.next */
		next.className = "next";
		next.appendChild(document.createTextNode(currentVideo.nextairing));

		/* Append all elements to div #xmp */
		xmp.appendChild(franchise);
		xmp.appendChild(title);
		xmp.appendChild(next);

		if(currentVideo.multiclipind != "Y") {
			/* All done. Now let TBS do it's thang... */
			/* Call this.XMP(); */
			this.XMP(currentVideo);
		}

	},

	Scenes : function(video) {
		if (video.multiclipind == "Y") {
			$.getJSON('/exclude/videoplayer/2007/genericVideoAggregator/0,,' + unescape(video.contentid) + ',00.html', function(data) {
				$('#sceneContent').empty().append('<div id="scene" class="carousel"><a class="trig previous" href="#"><span></span>previous</a><div class="frame episodes"><ul class="pane"></ul></div><a class="trig next" href="#"><span></span>next</a></div>');
				TBS.CurrentVideoPos++;
				$.each(data.videos, function(i, video) {
					// Add a scene flag
					video.isscene = i + 1;

					// Splice in clips to Video object
					TBS.Video[0].videos.splice((TBS.CurrentVideoPos + i), 0, video);
					$('#scene ul.pane').append('<li><a href="' + unescape(video.url) + '" title="' + video.cliptitle + '" class="play"><img src="' + video.thumbnailpath + '" alt="' + video.cliptitle + '" />' + video.cliptitle + '</a></li>');
				});
				$('#scene.carousel a.play:first').addClass("active");

				$('#scene.carousel')[0].isCarousel = false;
				TBS.Scenes.car = null;
				TBS.Scenes.car = new Carousel($('#scene.carousel')[0]);

				video = TBS.Video[0].videos[TBS.CurrentVideoPos];
				TBS.DoPlay(video);
			});
		} else {
			$('#sceneContent').empty().append('<div id="scene" class="carousel"><a class="trig previous" href="#"><span></span>previous</a><div class="frame episodes"><ul class="pane"></ul></div><a class="trig next" href="#"><span></span>next</a></div>');

			$('#scene ul.pane').append('<li><a href="' + unescape(video.url) + '" title="' + video.cliptitle + '" class="play active"><img src="' + video.thumbnailpath + '" alt="' + video.cliptitle + '" />' + video.cliptitle + '</a></li>');

			$('#scene.carousel')[0].isCarousel = false;
			$('#scene.carousel')[0].car = new Carousel($('#scene.carousel')[0]);

			TBS.DoPlay(video);
		}
	},

	Current : function() {
		var video = TBS.CurrentVideo;

		if (video) {
			var i;
			for (i = 1; video.isscene; i++) {
				video = TBS.Video[0].videos[TBS.CurrentVideoPos - i];
			}

			var play = $("#shows .show .options .play"), j;
			for (i = 0, j = play.length; i < j; i++) {
				var show = play[i];

				if (unescape($(show).attr("href")) == unescape(video.url)) {
					var exists = true;
					$(show).parents(".show").addClass("active")/* .siblings(".active").removeClass("active")*/;
					break;
				}
			}

			var to = $('.queue.now-playing')[0] ? '.queue.now-playing' : '.show.active';
			if($('.franchise .customScroll')[0] && $('.franchise .customScroll')[0].scrollTo) {
				$('.franchise .customScroll')[0].scrollTo(to);
			}
			/*var timeout = function() {
				if (_timer) {
					clearTimeout(_timer);
				}
				if($('.franchise .customScroll')[0] && $('.franchise .customScroll')[0].scrollTo) {
					$('.franchise .customScroll')[0].scrollTo('.queue.now-playing');
				} else {
					var _timer = setTimeout(timeout, 100);
				}
			};
			setTimeout(timeout, 100);*/
		}
	},

	/* Used to stop a video. Call to allow user to play another video */
	Stop : function() {
		/* TBS.Stop() was called, a video is not playing */
		this.VideoIsPlaying = false;
	},

	/* Used to pause a video. Call to allow user to play another video */
	Pause : function() {
		/* TBS.Pause() was called, a video is not playing */
		handleScrubbarEvent('pause');
	},

	/* Used to resume a video, after pausing */
	Resume : function() {
		handleScrubbarEvent('play');
	},

	/* Used to play the previous queued video (if needed) */
	Prev : function() {
		/* Now trigger TBS.Active to play active video */
		this.Active("prev");
	},

	/* Used to play the next queued video (if needed) */
	Next : function() {
		/* Now trigger TBS.Active to play active video */
		this.Active("next");
	},

	/* Used to target the active video (via ".active" class name) */
	Active : function(dir) {
		var videos = TBS.Video[0].videos,
		    current = videos[TBS.CurrentVideoPos],
		    play = $("#shows .show .options .play"),
		    scene = $("#scene li .play");

		if (dir == "next") {
			if (videos[TBS.CurrentVideoPos + 1]) {
				/* User has explicitly triggered this video to play */

				/* Stop the current video from playing (if any) */
				TBS.Stop();

				/* At long last, trigger TBS.Play(); */
				TBS.Play(unescape(videos[TBS.CurrentVideoPos + 1].url));

			} else {
				return;
			}
		} else if (dir == "prev") {
			if (videos[TBS.CurrentVideoPos - 1]) {
				/* User has explicitly triggered this video to play */

				/* Stop the current video from playing (if any) */
				this.Stop();

				/* At long last, trigger TBS.Play(); */
				TBS.Play(unescape(videos[TBS.CurrentVideoPos - 1].url));

			} else {
				return;
			}
		}

		/* Check if link exists in page */
		var i;
		for (i = 0, j = play.length; i < j; i++) {
			if (unescape($(play[i]).attr("href")) == unescape(TBS.CurrentVideo.url)) {
				PlaylistScroll.dirTrigger(dir);
				break;
			}
		}
		for (i = 0, j = play.length; i < j; i++) {
			if (unescape($(scene[i]).attr("href")) == unescape(TBS.CurrentVideo.url)) {
				$('#scene li .active').removeClass("active");
				$(scene[i]).addClass("active");
			}
		}
	},

	/* For TBS use. Used to tie in XMP functionality (TBS.Play() calls this after it's done) */
	XMP : function(e) {
		/* Set currentVideo to "e" */
		var currentVideo = e;

		// if lastTrackedVideo exists, then send a VideoCensus end beacon here (means the last played video didn't finish)
		if (lastTrackedVideo.videoId != undefined) {
			// VideoCensus ("dav2-" means end)
			var ScImgSrc;
			var ScRandom = Math.ceil(Math.random()*1000000000);
			ScImgSrc = 'http://secure-us.imrworldwide.com/cgi-bin/m?ci=us-100429';
			ScImgSrc += '&tl=dav2-' + escape(lastTrackedVideo.videoId + " / " + lastTrackedVideo.videoTitle);
			ScImgSrc += '&cg=' + escape(lastTrackedVideo.franchiseName);
			ScImgSrc += '&c6=vc,c05' + escape('');
			ScImgSrc += '&cc=1';
			ScImgSrc += '&rnd=' + ScRandom;

			var davImg = "";
			davImg = new Image();
			davImg.src = ScImgSrc;

			lastTrackedVideo = new Object();
		}

		/* Call XMP Here */
		if (driver !== null && driver !== "") {
			handleAddPlaylistItem(currentVideo.videopath);
		} else {
			waitingVideo = currentVideo.videopath;
		}
	},

	/* Omniture tracking */
	TrackOmniture : function(obj) {
    window.s = window.s || {tl : function(){}, t : function(){}};
		s.server = (obj.server != undefined) ? obj.server : "";
		s.channel = (obj.channel != undefined) ? obj.channel : "";
		s.pageName = (obj.page != undefined) ? obj.page : "";
		s.prop1 = (obj.prop1 != undefined) ? obj.prop1 : "";
		s.prop2 = (obj.prop2 != undefined) ? obj.prop2 : "";
		s.prop3 = (obj.prop3 != undefined) ? obj.prop3 : "";
		s.prop4 = (obj.prop4 != undefined) ? obj.prop4 : "";
		s.prop5 = (obj.prop5 != undefined) ? obj.prop5 : "";
		s.prop6 = (obj.prop6 != undefined) ? obj.prop6 : "";
		s.prop13 = (obj.prop13 != undefined) ? obj.prop13 : "";
		s.prop14 = (obj.prop14 != undefined) ? obj.prop14 : "";
		s.prop15 = (obj.prop15 != undefined) ? obj.prop15 : "";
		s.prop16 = (obj.prop16 != undefined) ? obj.prop16 : "";
		s.events = (obj.events != undefined) ? obj.events : "";
		s.eVar2 = (obj.eVar2 != undefined) ? obj.eVar2 : "";

		s.eVar1 = s.pageName;
		s.eVar3 = s.eVar2;
		s.eVar7 = s.prop4;
		s.eVar8 = s.prop1;
		s.eVar9 = s.prop2;
		s.eVar10 = s.channel;
		s.eVar14 = s.prop14;
		s.eVar15 = s.prop15;
		s.eVar16 = s.prop16;
		s.linkTrackEvents=s.events;

		if (obj.page == "") {
			// track as event
			s.tl(obj.prop1, 'o', 'video link');
		} else {
			// track as page
			s.t();
		}
	}
};

/**
 * @author Richard Herrera
 * @method StateManager
 *
 * Triggers StateManager
 */
/* Create a global StateManager shortcut */
var StateManager = EXANIMO.managers.StateManager;

/* Load a page onstaterevisit */
StateManager.onstaterevisit = function(e) {
	Page.load(e.id);
};

/* Initialize StateManager onload */
$(window).load(function() {
	StateManager.initialize(false, StateManager);
});

/**
 * @author Richard Herrera
 * @method Overlay
 *
 * Show / Hide / Initialize the "loading" state
 */
$(document).ready(function() {
	Overlay.init();
});
var Overlay = {
	init : function() {
		/* Create the elements needed to "load", then hide them until necessary */
		$('<div id="loading"><span class="img"></span></div><div id="loading_bg"></div>').appendTo("#main").hide();

		/* Set the opacity to 80% */
		$("#loading_bg").css("opacity", 0.8);
	},
	show : function() {
		/* Show all divs whose id begins with "loading" */
		$("div[id^=loading]").show();
	},
	hide : function() {
		/* Hide all divs whose id begins with "loading" */
		$("div[id^=loading]").hide();
	}
};

/**
 * @author Michael Bester
 * @namespace Scroll
 *
 * Custom Scroller options. DO NOT MODIFY.
*/
var Scroll = {
	options : {
		scrollbarWidth : 15,
		dragMaxHeight : 24,
		dragMinHeight : 24
	},
	animate : {
		scrollbarWidth : 15,
		dragMaxHeight : 24,
		dragMinHeight : 24,
		animateTo : true,
		animateInterval : 30,
		animateStep : 3
	}
};

/**
 * @author Richard Herrera
 * @method Page
 *
 * A utility namespace, loads HTML and fires functions onDOMContentLoaded
 */
/* $(document).ready(function() {
	Page.dom();
}); */
var Page = {
	load : function(e) {
		/* Call Overlay */
		Overlay.show();

		/* Set some local variables */
		var href, rel, home, featured,
		    dir = TBS.Directory;

		/* If a parameter is passed, grab the element's rel attribute */
		if (e) {
			if (typeof e == "string") {
				href = e;
			} else {
				href = $(e).attr("rel");
				if (e == TBS.FeaturedVideo) {
					href = TBS.FeaturedVideo;
				}
			}

		/* Otherwise, grab the necessary parameter from location.hash */
		} else {
			if (location.hash) {
				href = location.hash.split("#")[1];
			} else {
				href = TBS.FeaturedVideo;
				featured = "/featured/";
				home = true;
			}
		}

		if (href == TBS.FeaturedVideo) {
			dir = "";
			featured = "/featured/";
		}
		dir = (href == TBS.FeaturedVideo) ? "" : dir;
		var hash = featured || href;

		/* Unless we're on the home page, set state with StateManager */
		if (!home) {
			StateManager.setState(hash || href);
		}

		rel = (StateManager.stateID || hash).split("/")[1];

		$("#nav-" + rel).addClass("active").siblings("li").removeClass("active").removeClass("inactive");
		if (rel == "all-video") {
			Navigation.prototype["all-video"].init(e);
			TBS.TrackOmniture({channel:"Videos", page:"Videos:" + hash, server:"Browse"});
			return;
		}
		if (rel == "my-playlist") {
			Playlist.load(true);
			return;
		}
		if (rel == "featured") {
			dir = "";
			href = TBS.FeaturedVideo;
			TBS.TrackOmniture({channel:"Videos", page:"Videos:" + hash, server:"Browse"});
		}

		// Check for contentID
		var num = href.replace(/\//g, ""),
		    string = parseInt(num).toString();
		if ((string != "NaN") && (string.length > 3)) {
			$.getJSON(TBS.PlaylistInfo + string, function(data) {
				if (!Navigation.JSON) {
					var cho = TBS.CHO;
					$.getJSON(cho, function(feed) {
						Navigation.JSON = {
							rel : ["", ""],
							active : data,
							combo : [],
							url : "",
							feed : feed
						};
						Navigation.prototype["all-video"].sub(data, true);
					});
				}
			});
		} else {
			$.ajax({
				url : unescape(dir + href),
				cache : true,
				success : function(data) {
					Page.html(data);
				}
			});
		}
	},
	html : function(data) {
		var dummy = document.createElement("div");
		dummy.innerHTML = data;

		var subnav = $("#main #subnav")[0];
		if ($(dummy).children("#subnav")[0]) {
			if (!subnav) {
				$(dummy).children("#subnav").insertBefore($("#main #content"));
			} else {
				$("#main #subnav").replaceWith($(dummy).children("#subnav"));
			}
		} else if (subnav) {
			$("#main #subnav").remove();
		}
		if ($("#playlist.playlist-expanded")[0]) {
			$("#main").removeClass("playlist-expanded").children("#playlist.playlist-expanded").remove();
		}
		if ($("#search.search-expanded")[0]) {
			$("#main").removeClass("expanded").children("#search.search-expanded").remove();
		}
		if ($(dummy).children("#content")[0]) {
			$("#main #content").replaceWith($(dummy).children("#content"));
		} else if ($(dummy).children("#playlist")[0]) {
			$(dummy).children("#playlist").insertAfter("#content");
			$("#playlist").toggle();
			$("#share_playlist").toggle();
			Playlist.widen();
			Playlist.play();
			Playlist.options();
			Playlist.actions();
			$("#playlist #shows .options .play").bind("click", function(e) {
				Playlist.play(this);
				e.preventDefault();
			});

		}
		if ($(dummy).find("#video-object")[0]) {
			Page.eval($(dummy).find("#video-object")[0]);
		}

		/* Call Overlay */
		Overlay.hide();

		Page.dom();
	},
	dom : function() {
		TBS.newpage = true;
		$('a[href=#]').click(function(e){e.preventDefault();});
		$('#main .carousel').each(function(){
			this.car = new Carousel(this);
		});
		$('.tabWrapper').each(function(){
			this.tabs = new Tabs(this);
		});
		$('#content.shows #shows').each(function() {
			var shows = $(this).children('.show'),
			    show = new Showlist(this, shows);
		});
		$("#subnav ul a").bind("click", function(e) {
			e.preventDefault();
			if (!$(this).hasClass("active")) {
				var n = new Navigation();
				n["all-video"].cho(this);
			}
		});

		/* Prettify scrollbars */
		$('.customScroll').jScrollPane(Scroll.options);
		$('.franchise .customScroll').jScrollPane(Scroll.animate);

		PlaylistScroll.init();
		$("#shows .play").bind("click", function(e) {
			e.preventDefault();
			Playlist.play(this);
		});
		$("#main .options .add").bind("click", function(e) {
			e.preventDefault();
			if (/#$/.test(this.href)) {
				return false;
			}
			var cookie = Playlist.cookie($(this), "add");
			var foo = $(this).parents(".show").clone(true).appendTo("#playlist #shows .me");
			var bar = ($(foo).find(".options li:first-child"));
			$('<li><a href="' + $(this).attr('href') + '" class="delete">DELETE<span></span></a></li>').insertAfter($(bar));
			$('<li><a href="#" class="up">MOVE UP<span></span></a></li><li><a href="#" class="down">MOVE DOWN<span></span></a></li>').insertBefore($(bar));
			($(foo).find(".options li:last-child")).remove();
			if ($('.playlist-expanded')[0]) {
				$(foo).find(".options li a span").remove();
			}
			Playlist.options();

			if (cookie) {
				var empty = document.getElementById("error_share_empty");
				if (empty) {
					empty.parentNode.removeChild(empty);
				}
			}

			episodetitle = $(this).parents(".show").children(".episodetitle").attr("value");
			contentid = $(this).parents(".show").children(".contentid").attr("value");
			TBS.TrackOmniture({eVar2:episodetitle + ":(" + contentid + ")", events:"event8"});
		});
		$('.paginate a').bind("click", function(e) {
			if (!$(this).hasClass("active")) {
				Page.load(this);
			}
			e.preventDefault();
		});
		$('#seasons a').bind("click", function(e) {
			Page.load(this);
			e.preventDefault();
		});

		$("#loading .img").ajaxError(function(request, settings) {
			var bg = $(this).css("background-image");
			$(this).css("background-image", "url(http://i.cdn.turner.com/v5cache/TBS/video/img/cmn/error.png)");

			setTimeout(function() {
				$("div[id^=loading]").fadeOut(function() {
					$("#loading .img").css("background-image", bg);
				});
				if (!($("#content").children().get(0))) {
					StateManager.setState("/all-video/");
					Page.load();
				}
			}, 2000);
		});
		TBS.Current();
	},
	eval : function(e) {
		if ((e.innerHTML).indexOf(TBS.JSON_ID) > 0) {
			eval(e.innerHTML);
		}
		/* User has NOT explicitly triggered this video */
		/* Check if VideoIsPlaying */
		if (!TBS.VideoIsPlaying) {
			/* If not, trigger chosen video to play */
			TBS.Play(window[TBS.JSON_ID]);
		}
	}
};

/**
 * @author Richard Herrera
 * @constructor Navigation
 *
 * Return false on primary navigation and fire a function
 * based on link rel attribute
 */
$(document).ready(function() {
	var nav = new Navigation(),
	    hash = location.hash;
	if (!hash) {
		hash = "featured";
		Page.load();
	} else {
		hash = hash.split("#")[1].split("/")[1];
	}
	var id = "#nav-" + hash;
	$(id).parent().children("li").removeClass("active").removeClass("inactive");
	$(id).addClass("active");
});
var Navigation = function(e) {
	this.e = $(e);
	this.init();
};
Navigation.prototype = {
	init : function() {
		var _this = this;
		$("#header ul a").bind("click", function(e) {
			var rel = $(this).attr("rel").split("/")[1];
			/* Call Overlay */
			Overlay.show();
			(_this[rel].init) ? _this[rel].init(this) : _this[rel](this);
			e.preventDefault();
		});
	},
	featured : function(e) {
		if ($(e).parent(".active")[0]) {
			Overlay.hide();
			return;
		}
		$(e).parent().parent().children("li").removeClass("active").removeClass("inactive");
		$(e).parent().addClass("active");
		if (Playlist.trig) {
			$("div[id^=playlist]").remove();
			Playlist.trig = false;
			$("#nav-my-playlist a").one("click", function() {
				Playlist.init();
			});
		}
		if (Search.trig) {
			$("div[id^=search]").remove();
			Search.trig = false;
		}
		Page.load(TBS.FeaturedVideo);
	},
	"all-video" : {
		init : function(e) {
			var _this = this;

			if (typeof e != "string") {
				$(e).parent().parent().children("li").removeClass("active").removeClass("inactive");
			}
			// if (!($("#content").hasClass("shows"))) {
				$(e).parent().addClass("active");
			// }
			if (Playlist.trig) {
				$("div[id^=playlist]").remove();
				Playlist.trig = false;
				$("#nav-my-playlist a").one("click", function() {
					Playlist.init();
				});
			}
			if (Search.trig) {
				$("div[id^=search]").remove();
				Search.trig = false;
			}
			if (typeof e == "string") {
				StateManager.setState(e);
			} else if (e) {
				StateManager.setState($(e).attr("rel"));
			}
			/* We only need the CHO once */
			if (!Navigation.JSON) {
				var cho = TBS.CHO;
				$.getJSON(cho, function(feed) {
					Navigation.JSON = {};
					Navigation.JSON.feed = feed;
					_this.handle(e);
				});
			} else {
				_this.handle(e);
			}
		},
		dom : function(data) {
			var _this = this;

			/* Call Overlay */
			Overlay.hide();

			Page.dom();
		},
		sub : function(data, e) {
			/* Safari loses its scope right around here.
			So we search for content and header the old-fashioned way
			And remove 'em before we continue. */
			var nodes = $("#main").children();
			$.each(nodes, function(i, node) {
				if (/content|subnav/.test($(node).attr("id"))) {
					$(node).remove();
				}
			});

			Navigation.Sub = true;

			var _this = this;
			var video = data.videos || data.subcategory,
			    rel = Navigation.JSON.rel,
			    url = unescape(Navigation.JSON.url),
			    object = Navigation.JSON.active,
			    parent = rel[1],
				deep = Navigation.JSON.deep,
			    subs = object.subcategory || data.subcategory,
			    pagination = '<div class="paginate top"></div>', i, j;

			if (!e) {
				$('<div id="subnav"></div>').addClass("alt").append('<div id="all"><h3><a id="allVideo" href="' + TBS.CHO + '" rel="/all-video/">ALL VIDEO</a></h3><ul><li><a class="shownav" rel="' + location.hash.split("#")[1].split(rel[2])[0] + '" href="' + location.hash.split("#")[1].split(rel[2])[0] + '">&gt; ' + rel[1].replace(/-/g, " ")  + '</a></li></ul></div><div id="subnav_btm></div>"').insertAfter("#header");

				$("a#allVideo").bind("click", function(e) {
					_this.init(this);
					e.preventDefault();
				});

				if (object.rel && object.franchise) {
					$('<li><a class="shownav franchise" rel="' + object.rel + '" href="' + unescape(object.url) + '">&gt; ' + object.franchise + '</a></li>').appendTo("#subnav #all > ul");
				}
				if (subs) {
					$('<ul></ul>').appendTo("#subnav li:last-child");

					$.each(subs, function(i, sub) {
						var name = sub.name || sub.franchise;
						var format = name.replace(/[^\w\d\s]/g, "").replace(/\-/g, '_').replace(/ +/g, "-");

						if ($("#subnav ul ul li").attr("class") != format) {
							if (rel[rel.length - 1] == format) {
								$(".shownav.franchise").removeClass("franchise");
								format += " active";
							}
							$('<li class="' + format + '"><a rel="' + object.rel + format + '/" href="' + unescape(sub.url) + '">' + name + '</a></li>').appendTo("#subnav ul ul");
						}
					});
					var sublime = $("#subnav ul ul li");
					for (i = 1, j = sublime.length; i < j; i = (i + 2)) {
						$(sublime[i]).addClass("alt");
					}
				}

				if (!($.browser.safari)) {
					for (i = 0, j = Navigation.JSON.combo.length; i < j; i++) {
						var combo = Navigation.JSON.combo[i];
						if (parent.replace(/-/g, " ") == combo.name.replace(/-/g, " ")) {
							var text = $(".shownav.franchise").get(0);
							text = $(text).text().replace("> ", "");
							if (combo.subcategory) {
								$.each(combo.subcategory, function(i, name) {
									if (text != name.franchise) {
										$('<li><a class="shownav" rel="' + name.rel + '" href="' + unescape(name.url) + '"> > ' + name.franchise + '</a></li>').appendTo("#subnav div > ul");
									}
								});
							}
						}
					}
				}

			} else {
				_this.menu(data);
			}

			var title = $('#subnav .active').text() || $('#subnav .franchise').text() || $('#subnav ul:first li:first .shownav').text() || "shows";
			title = (/\>/.test(title)) ? title.replace(">", "") : title;

			$('<div id="content"></div>').attr("class", "franchise").append('<h1>' + title + '</h1><h2>videos [' + data.total + ']</h2><div id="pagination">' + pagination + '</div><div id="shows" class="customScroll"></div>').insertAfter("#subnav");

			var exists;
			$.each(data.videos, function(i, item) {
				$("#shows").append('<div class="show"><ul class="options"><li><a href="' + unescape(item.url) + '" class="play" title="play">PLAY<span></span></a></li><li><a href="' + unescape(item.url) + '" class="add" title="add to playlist">ADD<span></span></a></li></ul><a href="' + unescape(item.url) + '" class="play"><img src="' + item.thumbnailpath + '" width="96" height="72" alt="" /></a><h4>' + item.episodetitle + '</h4><p>' + item.clipdescription + '</p><input type="hidden" class="episodetitle" value="' + item.episodetitle + '"><input type="hidden" class="contentid" value="' + item.contentid + '"></div>');


				/* Find TBS.CurrentVideo */
				/* If we've stored a deep link */
				if (deep) {

					/* Then test for that id string in the current item's url parmeter */
					if (new RegExp(deep).test(unescape(item.url))) {

						/* If it exists, set our CurrentVideo */
						exists = unescape(item.url);
					}
				}

			});

			$("#shows .show:last-child").addClass("last-child");

			_this.next = function() {
				$("#shows").after(pagination.replace('top','bottom'));

				var pages = Math.ceil(parseInt(data.total, 10) / TBS.VideosPerPage),
				    currentPage, nextPage, prevPage;

				url = url.split("?")[0];

				if (/page\-\d/.test(rel.join())) {
					var o = rel.join().match(/page\-(\d)/)[1];
					currentPage = parseInt(o, 10);
					rel.pop();
				} else {
					currentPage = 1;
				}

				if (data.seasons) {
					$('<div id="seasons">season: all <span class="alt">|</span><span class="cap"></span></div>').insertBefore("#pagination");
					var seasons = parseInt(data.seasons, 10);
					for (i = 0, j = seasons; i < j; i++) {
						var s = (i + 1);
						$('<a href="' + unescape(url) + '?season=' + s + '" rel="/' + rel.join("/") + '/season-' + s + '/" class="alt"> ' + s + ' </a>').insertBefore("#seasons .cap");
						if (s != seasons) {
							$('<span class="alt">|</span>').insertBefore("#seasons .cap");
						}
					}
				}

				if (pages > 1) {
					prevPage = (currentPage - 1);
					nextPage = (currentPage + 1);

					if (prevPage > 0) {
						$('<a href="' + unescape(url) + '?page=' + prevPage + '" rel="/' + rel.join("/") + '/page-' + prevPage + '/">&lt; prev</a>').prependTo(".paginate");
					}
					if (nextPage < (pages + 1)) {
						$('<a href="' + unescape(url) + '?page=' + nextPage + '" rel="/' + rel.join("/") + '/page-' + nextPage + '/">next &gt;</a>').appendTo(".paginate");
					} else {
						$('<a href="#" class="hide"></a>').appendTo(".paginate");
					}

					for (i = 0, j = pages; i < j; i++) {
						var active = ((i + 1) == currentPage) ? 'active' : 'alt';
						$('<a href="' + unescape(url) + '?page=' + (i + 1) + '" rel="/' + rel.join("/") + '/page-' + (i + 1) + '/" class="' + active + '">' + (i + 1) + '</a>').insertBefore(".paginate a:last-child");
						if ((i + 1) != pages) {
							$('<span class="alt">|</span>').insertBefore(".paginate a:last-child");
						}
					}
				}

				$('<h3 class="queue now-playing">now playing</h3>').insertBefore("#content #shows .show.active");

				// No play if all-video root

				/* Assign data.videos object to TBS object */
				window[TBS.JSON_ID] = data;

				/* User has NOT explicitly triggered this video */
				/* Check if VideoIsPlaying */
				if (!TBS.VideoIsPlaying) {

					/* Set current video */
					TBS.Current();

					/* If not, trigger chosen video to play */
					TBS.Play(window[TBS.JSON_ID]);
				}

				_this.dom(data);
			};

			if (deep && !TBS.VideoIsPlaying) {
				if (!exists) {
					$.getJSON(TBS.PlaylistInfo + deep, function(data) {
						var item = data.videos[0];

						// var franchise = item.franchise.replace(/ /g, "-").toLowerCase(), inURL;
						// for (var i = 0, j = rel.length; i < j; i++) {
						// 	if (franchise == rel[i]) {
						// 		inURL = true;
						// 		break;
						// 	}
						// }
						// if (inURL) {
							// $("#shows").prepend('<div class="show"><ul class="options"><li><a href="' + item.url + '" class="play" title="play">PLAY<span></span></a></li><li><a href="' + item.url + '" class="add" title="add to playlist">ADD<span></span></a></li></ul><a href="' + item.url + '" class="play"><img src="' + item.thumbnailpath + '" width="96" height="72" alt="" /></a><h4>' + item.episodetitle + '</h4><p>' + item.clipdescription + '</p><input type="hidden" class="episodetitle" value="' + mine.episodetitle + '"><input type="hidden" class="contentid" value="' + mine.contentid + '"></div>');
							/* User has explicitly triggered this video to play */
							/* Stop the current video from playing (if any) */
							TBS.Stop();

							TBS.Video = [data];

							/* Trigger chosen video to play */
							TBS.Play(unescape(item.url));
						// }

						_this.next();
					});
				} else {
					/* User has explicitly triggered this video to play */
					/* Stop the current video from playing (if any) */
					TBS.Stop();

					TBS.Video = [data];

					/* Trigger chosen video to play */
					TBS.Play(exists);
					_this.next();
				}
				Navigation.JSON.deep = false;
			} else {
				_this.next();
			}

		},
		root : function(data) {
			/* Safari loses its scope right around here.
			So we search for content and header the old-fashioned way
			And remove 'em before we continue. */
			var nodes = $("#main").children();
			$.each(nodes, function(i, node) {
				if (/subnav|content/.test($(node).attr("id"))) {
					$(node).remove();
				}
			});

			Navigation.Sub = false;

			var _this = this;
			var video = data.videos || data.subcategory,
			    feed = Navigation.JSON.feed,
			    rel = Navigation.JSON.rel,
			    title = Navigation.JSON.title;

			$('<div id="content"></div>').attr("class", "shows").append('<h1>' + title + ' <em>[' + video.length + ']</em></h1><div id="shows" class="customScroll">').insertAfter("#header");

			_this.menu(data);

			$.each(video, function(i, item) {
				item.num = item.num || {};
				$("#shows").append('<div class="show"><img src="' + item.thumbnailpath  + '" width="96" height="72" alt="" /></div>');

				if (item.seasonnum) {
					$("#shows .show:last-child").append('<p>season ' + item.seasonnum + '</p>');
				}
				if (item.episodenum) {
					$("#shows .show:last-child p").append(', ' + 'episode ' + item.episodenum);
				}
				if (item.episodetitle) {
					$("#shows .show:last-child p").append(': ' + item.episodetitle);
				}

				$("#shows .show:last-child").append('<h2><a href="' + unescape(item.url) + '" rel="' + item.rel + '">' + item.franchise + '</a></h2><ul></ul>');

				if (item.subcategory) {
					for (k = 0, j = item.subcategory.length; k < j; k++) {
						var sub = item.subcategory[k];
						if (k < 5) {
							$('<li>' + sub.name + '</li>').appendTo("#shows .show:last-child ul");
						} else {
							$('<li>more</li>').appendTo("#shows .show:last-child ul");
							break;
						}
					}
				}

			});
			_this.dom(video);
		},
		menu : function(data) {
			var _this = this;
			var feed = Navigation.JSON.feed,
			    rel = Navigation.JSON.rel,
			    title = Navigation.JSON.title;
			$("#subnav").remove();
			$('<div id="subnav"></div>').removeClass("alt").append('<div id="type"><h3>BROWSE BY TYPE</h3><ul></ul></div><div id="subject"><h3>BROWSE BY SUBJECT</h3><ul></ul></div><div id="quick"><h3>QUICK PICKS</h3><ul></ul></div>').insertAfter("#header");
			$.each(feed.type, function(i, item) {
				$("#subnav #type ul").append('<li class="' +  item.name.replace(/ /g, "-") + '"><a href="' + item.rel + '" rel="' + item.rel + '">' + item.name + '<span></span></a></li>');
			});
			$.each(feed.subject, function(i, item) {
				$("#subnav #subject ul").append('<li class="' +  item.name.replace(/ /g, "-") + '"><a href="' + item.rel + '" rel="' + item.rel + '">' + item.name + '<span></span></a></li>');
			});
			$.each(feed.quick, function(i, item) {
				$("#subnav #quick ul").append('<li class="' +  item.name.replace(/ /g, "-") + '"><a href="' + item.rel + '" rel="' + item.rel + '">' + item.name + '<span></span></a></li>');
			});
			var li = $("#subnav li");
			for (var i = 0, j = li.length; i < j; i = i + 2) {
				$(li[i]).addClass("alt");
			}
			if (rel[1]) {
				$("#subnav ul li." + (rel[1].replace(/ /g, "-"))).children("a").addClass("active");
			} else {
				$("#subnav ul li.shows a").addClass("active");
			}

			return $("#subnav ul a.active")[0];
		},
		handle : function(e) {
			var _this = this;
			if ($("#playlist.playlist-expanded")[0]) {
				$("#main").removeClass("playlist-expanded").children("#playlist.playlist-expanded").remove();
			}
			if ($("#search.search-expanded")[0]) {
				$("#main").removeClass("expanded").children("#search.search-expanded").remove();
			}

			var feed = Navigation.JSON.feed;
			var hash = location.hash.split("#")[1] || "";
			var rel = hash.split("/"),
			    newRel = [], sub, category, i, j;
			for (i = 0, j = rel.length; i < j; i++) {
				if (rel[i] !== "") {
					newRel.push(rel[i]);
				}
			}

			rel = newRel;
			Navigation.JSON.rel = rel;
			if (!rel[1]) {
				rel[1] = "shows";
			}

			var combo = [];
			$.each(feed.type, function(i, item) {
				combo.push(item);
			});
			$.each(feed.subject, function(i, item) {
				combo.push(item);
			});
			$.each(feed.quick, function(i, item) {
				combo.push(item);
			});
			Navigation.JSON.combo = combo;

			var trueNum, trueQuery;
			$.each(rel, function(i, num) {
				var string = parseInt(num).toString();
				if ((string != "NaN") && (string.length > 3)) {
					trueNum = num;
				}
				if (/offset|length/.test(num)) {
					trueQuery = num;
				}
			});
			if (trueNum) {
				Navigation.JSON.deep = trueNum;
			}
			if (trueQuery) {
				Navigation.JSON.query = trueQuery;
			}

			if (rel[2] || (rel[1] != "shows")) {
				var url, active, title, subnum;
				$.each(combo, function(i, item) {
					if ((new RegExp(rel[1])).test(item.rel)) {
						title = rel[1];
						active = item;
						url = item.startfeed;
						var _sub = item.subcategory;
						if (_sub && rel[2]) {
							$.each(_sub, function(i, item) {
								var foo = rel[2].replace(/-/g, " ");
								if ((new RegExp(foo)).test(item.franchise)) {
									title = rel[2];
									url = item.url;
									subnum = true;

									_sub = item.subcategory;
									if (_sub && rel[3]) {
										$.each(_sub, function(i, item) {
											var bar = item.name.replace(/[^\w\d\s]/g, "").replace(/\-/g, '_').replace(/ +/g, "-");
											if (bar == rel[3]) {
												title = rel[3];
												url = item.url;
												subnum = true;
											}
										});
									}
									active = item;
								}
							});
						}
					}
				});

				var subcat = 0;
				$.each(combo, function(i, item) {
					if ((new RegExp(rel[1])).test(item.rel)) {
						subcat = 1;
						if (item.subcategory) {
							$.each(item.subcategory, function(i, item) {
								if (item.subcategory) {
									$.each(item.subcategory, function(i, item) {
										subcat = 2;
									});
								}
							});
						}
					}
				});
				if (title) {
					title = title.replace(/-/g, " ");
				}

				if (e && $(e).attr("href")) {
					url = $(e).attr("href").split("?")[0];
				}

				var page = location.hash.split("page-")[1],
				    which = (/\?/.test(url)) ? "&" : "?";
				if (page) {
					page = page.split("/")[0];
					url += which + "offset=" + ((parseInt(page) - 1) * TBS.VideosPerPage) + "&length=" + TBS.VideosPerPage;
				} else if (trueQuery) {
					url += trueQuery;
				} else {
					url += which + "offset=0&length=" + TBS.VideosPerPage;
				}

				Navigation.JSON.title = title;
				Navigation.JSON.active = active;
				Navigation.JSON.url = unescape(url);

				/* If the element passed has an empty href, return */
				if ($(e).attr("href") == "#") {
					Overlay.hide();
					return;
				}
				if (!url || !(/,|\||html/.test(url))) {
					var n = new Navigation();
					n["all-video"].cho();
					return;
				}
				$.getJSON(url, function(data) {
					if (!data.videos) {
						Overlay.hide();
						return;
					}
					if (e) {
						StateManager.setState((typeof e == "string") ? e : $(e).attr("rel"));
					}

					Navigation.JSON.data = data;

					if (subnum || data.videos) {
						/* We're in a subcategory */
						_this.sub(data);
					} else {
						_this.root(data);
					}
				});
			} else {
				if (e) {
					StateManager.setState((typeof e == "string") ? e : $(e).attr("rel"));
				}

				Navigation.JSON.title = "shows";
				_this.root(feed.subject[0]);
			}

		},
		cho : function(e) {

			var _this = this;

			if (!e) {
				e = $("#subnav ul a.active")[0] || _this.menu();
			}

			if ($("#subnav").hasClass("alt")) {
				Page.load(e);
				return;
			}

			var _parent = $(e).parent().parent().parent().attr("id"),
		       _child = $(e).text(),
		       _feed = Navigation.JSON.feed;

			if (!_parent) {
				return;
			}

			for (var i = 0, j = _feed[_parent].length; i < j; i++) {
				var sub = _feed[_parent][i];
				if (sub.name == _child) {

					$("#subnav").find("a").removeClass("active");
					$(e).addClass("active");

					var subcategory = sub.subcategory;

					if (subcategory && subcategory.length > 1) {

						StateManager.setState((typeof e == "string") ? e : $(e).attr("rel"));

						$("#content").empty().attr("class", "shows").append('<h1>' + sub.name + ' <em>[' + subcategory.length + ']</em></h1><div id="shows" class="customScroll">');

						$.each(subcategory, function(i, item) {
							item.num = item.num || {};
							$("#shows").append('<div class="show"><img src="' + item.thumbnailpath  + '" width="96" height="72" alt="" /></div>');

							if (item.seasonnum) {
								$("#shows .show:last-child").append('<p>season ' + item.seasonnum + '</p>');
							}
							if (item.episodenum) {
								$("#shows .show:last-child p").append(', ' + 'episode ' + item.episodenum);
							}
							if (item.episodetitle) {
								$("#shows .show:last-child p").append(': ' + item.episodetitle);
							}

							$("#shows .show:last-child").append('<h2><a href="' + item.url + '" rel="' + item.rel + '">' + item.franchise + '</a></h2><ul></ul>');

							if (item.subcategory) {
								for (var k = 0, j = item.subcategory.length; k < j; k++) {
									var sub = item.subcategory[k];
									if (k < 5) {
										$('<li>' + sub.name + '</li>').appendTo("#shows .show:last-child ul");
									} else {
										$('<li>more</li>').appendTo("#shows .show:last-child ul");
										break;
									}
								}
							}

						});
						_this.dom(subcategory);
					} else if (sub.startfeed) {
						Page.load($('<a href="' + unescape(sub.startfeed) + '" rel="' + sub.rel + '"></a>'));
					} else {
						Page.load($('<a href="' + unescape(subcategory[0].url) + '" rel="' + subcategory[0].rel + '"></a>'));
					}

					break;
				}
			}
		}
	},
	"my-playlist" : function(e) {
		if ($(e).parent(".active")[0]) {
			Overlay.hide();
			return;
		}
		if (Playlist.expanded) {
			if(Search.trig) {
				Search.prototype.toggle();
			} else {
				Playlist.expanded = false;
				Playlist.init();
			}
		}
	}
};

/**
 * @author David Zuch
 * @constructor Carousel
 *
 * Pass each HTML element with a class of "carousel" to the constructor when
 * the document is ready.
 */
var Carousel = function(el) {
	/* make sure that elements only get passed to the constructor once */
	if(el.isCarousel) {
		return;
	}
	el.isCarousel = true;
	this.el = $(el);
	this.el.children(".inactive").removeClass("inactive");
	this.init();
};
Carousel.prototype = {
	init : function() {
		/* define elements */
		this.fr = $('.frame', this.el[0]);
		this.pane = $('.pane', this.el[0]);
		this.trigs = $('.trig', this.el[0]);

		if(!$('li', this.pane[0])[0]) {
			return;
		}

		/* define various paramaters */
		this.count = this.pane.children('li').length;
		if(this.el.width() === 0) {
			this.el.parents('.video_data').show();
			this.w = $('li', this.pane[0])[0].scrollWidth;
			this.inview = Math.floor(this.el.width() / this.w);
			this.el.parents('.video_data').hide();
		} else {
			this.w = $('li', this.pane[0])[0].scrollWidth;
			this.inview = Math.floor(this.el.width() / this.w);
		}
		this.limit = (this.count - this.inview);
		this.i = 0;

		/* set initial styles */
		this.fr.css('overflow', 'hidden');
		this.fr.css('position', 'relative');
		this.pane.css('overflow', 'hidden');
		this.pane.css('position', 'relative');
		this.pane.width(this.w * (this.count * 4 /* FF rendering issue*/) + 'px');

		/* create a self reference */
		var _this = this;

		/* if there's an active carousel item, highlight and slide to it */
		/*var active = _this.el.find("ul.pane li a.active")[0];
		if (active) {
			_this.slide(active);
		}*/
		if(_this.el[0].id !== "scene") {
			_this.el.find(".frame li a").bind("click", function(e) {
				TBS.Stop();
				e.preventDefault();
				Page.load(this);
			});
		} else {
			_this.el.find("a.play").bind("click", function(e) {
				e.preventDefault();
				_this.el.find("a.play").removeClass("active");
				$(this).addClass("active");
				TBS.Stop();
				TBS.Play(this.href);
			});
		}

		/* loop through each trigger and add event handlers */
		for (var i = 0, j = this.trigs.length; i<j; i++) {
			$(this.trigs[i]).bind('mouseover',function(){
				if(/inactive/.test(this.className)) {
					return;
				}
				$(this).children("span").addClass("over");
			});
			$(this.trigs[i]).bind('mouseout',function(){
				if(/inactive/.test(this.className)) {
					return;
				}
				$(this).children("span").removeClass("over");
			});
			$(this.trigs[i]).click(function(event){
				event.preventDefault();
				if(/inactive/.test(this.className)) {
					return;
				}
				_this.slide(this);
			});
		}

		/* call setClass method */
		this.setClass();
	},
	slide : function(el) {
		/* determine which direction to slide to and then slide there */
		if (!$(el).hasClass("trig")) {
			while(el && !$(el).hasClass("trig")) {
				el = el.parentNode;
			}
		}
		var to;
		if ($(el).hasClass("previous")) {
			if(this.i > 0) {
				this.i = this.i - this.inview;
				to = '+=' + (this.w * this.inview);
			}
		} else if ($(el).hasClass("next")) {
			if(this.i < this.limit) {
				this.i = this.i + this.inview;
				to = '-=' + (this.w * this.inview);
			}
		}
		if (to && to !== parseInt(this.pane.css('left'), 10)) {
			this.pane.animate({
				left: to
			}, 'slow');
		}
		this.setClass();
	},
	setClass : function() {
		/* set appropriate classes */
		var _this = this;
		$.each(this.trigs, function(i, trig) {
			if ($(trig).hasClass("previous")) {
				if(_this.i <= 0) {
					$(trig).addClass('inactive');
					$(trig).children("span").removeClass("over");
				}
				else {
					$(trig).removeClass('inactive');
				}
			} else if ($(trig).hasClass("next")) {
				if(_this.i >= _this.limit) {
					$(trig).addClass('inactive');
					$(trig).children("span").removeClass("over");
				}
				else {
					$(trig).removeClass('inactive');
				}
			}
		});
	}
};

/**
 * @author Richard Herrera, David Zuch
 * @constructor Tabs
 *
 * Create a new Tab instance for each link
 */
var Tabs = function(el) {
	this.el = $(el);
	this.init();
};
Tabs.prototype = {
	init : function() {

		/* create a self reference */
		var _this = this;

		/* define various paramaters */
		this.tabs = $('.tabs li', this.el);
		this.co = $('.tabContent', this.el);
		this.coAreas = $('/div', this.co);

		/* hide tab content */
		var i, j, cur;
		for (i=0, j=this.coAreas.length; i<j; i++) {
			cur = this.coAreas[i];
			$(cur).css('display', 'none');
		}
		$(this.co).height(0);
		$(this.co).children().hide();
		$(this.co).css('overflow', 'hidden');

		/* set up relations between elements and add event handlers */
		for (i=0, j=this.tabs.length; i<j; i++) {
			cur = this.tabs[i];
			cur.coId = $('a:first', cur)[0].href.split('#')[1];
			cur.co = $('#' + cur.coId);
			$(cur).hover(function() {
				if (this.coId === "shareContent") {
					$("#share_video").show();
					$("#share_video_result").hide();
				}
				_this.doSlideDown(this);
				$(this.co).hover(function() {
					clearTimeout(_this.timer);
				}, function() {
					_this.doSlideUp();
				});
			}, function() {
				if (this.coId === "shareContent") {
					$("#share_video").show();
					$("#share_video_result").hide();
				}
				_this.doSlideUp();
			});
			$(cur).click(function(event) {
				event.preventDefault();
				clearTimeout(_this.timer);
				_this.doSlideDown(this);
				_this.pressed = true;
			});
		}

		/* Set up clipboard copying on the "grab" tab */
		$("#grabContent input[@type='image'][@alt='Copy']").bind('click', function(e){
			var inp = $(this).prev('input[@type=text]');
			TBS.Util.copyToClipboard(inp[0]);
			inp.css("background-color","#f47b20");
			window.setTimeout(function(){
				inp.css("background-color","#ffffff");
			},50);
			e.preventDefault();

			if (inp[0].value.substring(0,7) == "http://") {
				TBS.TrackOmniture({eVar2:TBS.CurrentVideo.episodetitle + ":(" + TBS.CurrentVideo.contentid + ")", events:"event5"});
			} else {
				TBS.TrackOmniture({eVar2:TBS.CurrentVideo.episodetitle + ":(" + TBS.CurrentVideo.contentid + ")", events:"event4"});
			}
		});

		/* Set up XHR submission on the video share form */
		$('#share_video').bind("submit", function(e) {
			var _form = this;
			$(_form).parents('.tabWrapper').each(function(i,wrapper){
				$(wrapper).find('li#nav_share').each(function(i, tab){
					_form.tabs = wrapper.tabs;
					_form.tab = tab;
				});
			});
			if (_form.allowSubmit) {
				var inputs = [];
				$(':input', this).each(function() {
				    inputs.push(this.name + '=' + escape(this.value));
				});

				/* create the message div if it doesn't exist. */
				if (!_form.messageContainer) {
					_form.messageContainer = $('<div id="share_video_result" class="message"></div>');
					$(_form).after(_form.messageContainer);
					_form.messageContainer.populate = function(response) {
						$(_form).fadeOut(400,function(){
							$(_form.messageContainer).html(response);
							$(_form.messageContainer).show();
							_form.tabs.doSlideDown(_form.tab);

							/* 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 = "";
						});
					};
				}

				//omniContent = currentVideo.episodetitle + ':(' + currentVideo.episodenum + ')';
				TBS.TrackOmniture({eVar2:TBS.CurrentVideo.episodetitle + ":(" + TBS.CurrentVideo.contentid + ")", events:"event6"});

				$.ajax({
					url : TBS.ShareVideoSubmission,
					data: inputs.join('&'),
					dataType : 'html',
					cache : false,
					error : function(req) {
						var msg = (req.readyState !== 4) ? "incomplete request" : req.statusText;
						_form.messageContainer.populate('<dl><dt>Whoops!</dt><dd>There was an error sending your request.</dd></dl><p>Please try again later.</p>');
					},
					success : function(html){
						_form.messageContainer.populate(html);
					}
				});
			}
			e.preventDefault();
		});


	},
	doSlideUp : function () {
		/* prepare to slide the content up */
		if(this.pressed) {
			return;
		}
		var _this = this;
		clearTimeout(this.timer);
		this.timer = setTimeout(function() {
			_this.doHide();
		}, 500);
	},
	doSlideDown : function (el) {
		/* prepare to show the content */
		this.pressed = false;
		var _this = this;
		clearTimeout(this.timer);
		if (!this.isAnimating) {
			this.doShow(el);
		} else {
			this.timer = setTimeout(function() {
				_this.doShow(el);
			}, 250);
		}
	},
	doShow : function(el) {
		var _this = this;
		if(el.tagName.toLowerCase() !== 'li') {
			while(el && el.tagName.toLowerCase() !== 'li') {
				el = el.parentNode;
			}
		}
		this.tabs.each(function() {
			$(this).removeClass('active');
			$(this.co).css('display', 'none');
			this.co.shown = false;
		});
		this.isAnimating = true;
		$(el).addClass('active');
		$(el.co).css({
			'display': 'block',
			'visibility': 'hidden',
			'height': 'auto'
		});
		$(this.co).animate({
			height: el.co[0].scrollHeight
		}, {
			queue: false,
			duration: 'fast',
			complete: function(){
				$(el.co).css({'visibility': 'visible'});
				_this.isAnimating = false;
			}
		});
	},
	doHide : function(el) {

		var _this = this;

		this.isAnimating = true;
		_this.tabs.each(function() {
			$(this).removeClass('active');
		});
		$(_this.co).animate({
			height: 0
		}, {
			queue: false,
			duration: 'fast',
			complete: function(){
				_this.isAnimating = false;
			}
		}).children().hide();
	},
	populate : function(vid) {
		// populate the info tab
		$("#infoNowPlaying").empty();
		if (vid.infoPath != '') {
			$('<dl><dt>NOW PLAYING:</dt><dd>' + vid.episodetitle + '</dd></dl><p>' + vid.clipdescription + '  <a href="' + vid.infoPath + '" target="_blank">related site</a></p>').appendTo("#infoNowPlaying");
		} else {
			$('<dl><dt>NOW PLAYING:</dt><dd>' + vid.episodetitle + '</dd></dl><p>' + vid.clipdescription + '</p>').appendTo("#infoNowPlaying");
		}

		// Now we need to update the "add" button on the "info" video tab
		var newadd = $('#add').html();
		$('#add').empty().append(newadd);
		$('#add .add').attr('href', vid.url);

		/* not needed anymore since we added the link at the end of the description
		// update the "i" (info) button link
		$('#info .info').attr('href', vid.infoPath);
		$('#info .info').attr('target', '_blank');
		*/

		// Add event handlers to the add button
		$("#add .add").bind("click", function(e) {
			e.preventDefault();
			if (/#$/.test(this.href)) {
				return false;
			}
			var cookie = Playlist.cookie($(this), "add");
			if(cookie) {
				$.getJSON(TBS.PlaylistInfo + this.href.split(/\||\,/g)[2], function(data) {
					var item = data.videos[0];
					var foo = $('<div class="show"><ul class="options"><li><a href="#" class="up" title="move item up">MOVE UP<span></span></a></li><li><a href="#" class="down" title="move item down">MOVE DOWN<span></span></a></li><li><a href="' + item.url + '" class="play" title="play">PLAY<span></span></a></li><li><a href="' + item.url + '" class="delete" title="remove from playlist">DELETE<span></span></a></li></ul><a href="' + item.url + '" class="play"><img src="' + item.thumbnailpath + '" width="96" height="72" alt="" /></a><h4>' + item.episodetitle + '</h4><p>' + item.clipdescription + '</p><input type="hidden" class="episodetitle" value="' + item.episodetitle + '"><input type="hidden" class="contentid" value="' + item.contentid + '"></div>').appendTo("#playlist #shows .me");
					var bar = ($(foo).find(".options li:first-child"));
					if ($('.playlist-expanded')[0]) {
						$(foo).find(".options li a span").remove();
					}
					Playlist.options();
				});

				var empty = document.getElementById("error_share_empty");
				if (empty) {
					empty.parentNode.removeChild(empty);
				}
			}
		});

		// populate the grab tab
		$("#grabContent input[@type='text']")[0].value = vid.url + "?eref=sharethisUrl";

		if (vid.embeddable === 'Y') {
			$("#grabEmbed").show();
			$("#grabContent input[@type='text']")[1].value = "<object width='260' height='280'>" + "<param name='movie' value='http://i.tbs.com/v5cache/TBS/TBS04/flash/static/tbs_player.swf' />" + "<param name='FlashVars' value='id=" + vid.contentid + "' /> "  + "<embed src='http://i.tbs.com/v5cache/TBS/TBS04/flash/static/tbs_player.swf' " + "FlashVars='id=" + vid.contentid + "'type='application/x-shockwave-flash' " + "width='260' height='280'></embed></object>";
		} else {
			$("#grabEmbed").hide();
		}

		// set the share tab url
		if ($("#shareContent input[@type='hidden']")[0]) {
			$("#shareContent input[@type='hidden']")[0].value = vid.url + "?eref=sharethisEmail";
		}

		// set the bookmark values
		var bookMarkTitle = vid.franchise + ": " + vid.episodetitle + " on TBS.com";
		if ($("#deliciousForm input[@type='hidden']")[0]) {
			$("#deliciousForm input[@type='hidden']")[0].value = vid.url + "?eref=sharethisDelicious";
			$("#deliciousForm input[@type='hidden']")[1].value = bookMarkTitle;

			$("#diggForm input[@type='hidden']")[0].value = vid.url + "?eref=sharethisDigg";
			$("#diggForm input[@type='hidden']")[1].value = bookMarkTitle;

			$("#facebookForm input[@type='hidden']")[0].value = vid.url + "?eref=sharethisFacebook";
			$("#facebookForm input[@type='hidden']")[1].value = bookMarkTitle;

			$("#simpyForm input[@type='hidden']")[0].value = vid.url + "?eref=sharethisSimpy";
			$("#simpyForm input[@type='hidden']")[1].value = bookMarkTitle;
		}
	}
};

/**
 * @author Richard Herrera, David Zuch
 * @constructor PlaylistScroll
 *
 * Create a new Tab instance for each link
 */
var PlaylistScroll = {
	init : function() {
		var _this = this;
		this.shows = ($("#shows")[0] ? "#shows" : ($(".shows")[0] ? ".shows" : false));
		this.now = $('.queue.now-playing').clone(true);
		this.next = $('.queue.coming-up').clone(true);

		$(this.shows + ' .show').each(function() {
			var el = this;
			$(el).find('a.play').click(function(e) {
				e.preventDefault();
				_this.el = el;
				_this.transition();
			});
		});
	},
	dirTrigger : function(dir) {
		if(!(/next|prev/).test(dir)) {
			return;
		}
		this.el = $(this.shows + ' .active')[dir+'All']('.show')[0];
		if (!this.el) {
			this.el = $(".show")[0];
		}
		this.transition();
	},
	transition : function() {
		$(this.shows + ' .queue').remove();
		$(this.shows + ' .active').removeClass('active');
		$(this.el).addClass('active').before(this.now);
		$(this.el).after(this.next);

		if (this.next) {
			(this.next.next()[0]) ? this.next.removeClass("hide") : this.next.addClass("hide");
		}

		var to = $('.queue.now-playing')[0] ? '.queue.now-playing' : '.show.active';

		if($('.franchise .customScroll')[0] && $('.franchise .customScroll')[0].scrollTo) {
			$('.franchise .customScroll')[0].scrollTo(to);
		}
	}
};

/**
 * @author Richard Herrera
 * @constructor Panic
 *
 * Render a faux Excel spreadsheet onclick
 */
$(document).ready(function() {
	var panic = new Panic();
});
var Panic = function() {
	this.init();
	this.img = TBS.FakeSpreadSheet;
};
Panic.prototype = {
	init : function() {
		var _this = this;
		$("#panic").click(function(e) {
			/* Fire the "oh snap" function :) */
			_this.oh.snap(_this);
			e.preventDefault();
		});
	},
	oh : {
		snap : function(_this) {
			TBS.Pause();
			$('object, embed').addClass('invisible');
			/* if our dummy div does not exist, create from scratch */
			if (!$("#fakeStuff")[0]) {
				_this.oh.create(_this);
			/* Otherwise, toggle the visibility */
			} else {
				$("#fakeStuff").toggle();
			}
		},
		create : function(_this) {
			$('<div id="fakeStuff"><img src="' + _this.img + '" alt="I ARE A FAKE" /></div>').height("100%").appendTo("body").click(function(e) {
				TBS.Resume();
				$('object.invisible, embed.invisible').removeClass('invisible');
				$("#fakeStuff").toggle();
			});
		}
	}
};

/**
 * @author Richard Herrera
 * @constructor Search
 *
 * The Search object handles anything attributed to searching the site.
 * It is "eerily similar" to the Playlist object :)
 */
$(document).ready(function() {
	$("#header form").bind("submit", function(e) {
		$("#search").remove();
		var s = new Search(this);
		e.preventDefault();
	}).bind("keypress", function(e) {
		var key = e.charCode ? e.carChode : e.keyCode ? e.keyCode : 0;
		if (key === 13) {
			$("#search").remove();
			var s = new Search(this);
			e.preventDefault();
		}
	});

	/* Text input box handling */
	var si = $('#search_videos');
	si.attr('rel',si[0].defaultValue);
	si.bind('focus',function(){
		this.value = (this.value === this.getAttribute("rel")) ? "" : this.value;
	});
	si.bind('blur',function(){
		this.value = (this.value === "") ? this.getAttribute("rel") : this.value;
	});
	si.bind('dblclick',function(){
		this.value = this.getAttribute('rel');
	});

});
var Search = function(e) {
	this.e = $(e);
	this.init();
};
Search.prototype = {
	init : function() {
		/* $("#nav-my-playlist").removeClass("inactive").removeClass("active"); */

		/* Call Overlay */
		Overlay.show();

		var _this = this,
		    _that = this.e;

		if (Search.trig) {
			$("div[id^=search]").remove();
			Search.trig = false;
		}

		var href = _this.href(_that);

		Search.currentPage = 1;
		Search.doOnce = true;

		_this.render(href);
	},
	href : function(e) {
		e = $(e).attr("href");
		if (e) {
			e = e.split("?page=")[1];
		} else {
			e = 0;
		}
		e = ((parseInt(e) - 1) * TBS.VideosPerPage);
		return e;
	},
	render : function(href) {
		var _this = this,
		    _that = this.e;

		var expanded = $("#search.search-expanded")[0] ? true : false;

		var pagenum = (href / TBS.VideosPerPage) + 1;
		pagenum = pagenum <= 0 ? 1 : pagenum;
		var prop13 = $("#search_videos").attr("value");

		$.ajax({
			type : "GET",
			url : TBS.SearchInfo,
			data : "query=" + $("#search_videos").attr("value") + "&offset=" + href + "&length=" + TBS.VideosPerPage,
			success : function(data) {

				data = eval("(" + data + ")");

				$("#search").empty();

				if (!$("#search")[0]) {
					$('<div id="search"></div>').appendTo("#main");
				}

				if (data.total == 0) {
					// No search results
					$("#search").append('<div id="search_tp"></div><div id="overlay"><h1>no results found</h1><p id="close"><a href="#">x<span></span></a></p><p>Your search for ' + $("#search_videos").attr("value") + ' returned zero results. Edit your search criteria and try again or select \'close\' to exit this message.</p></div><div id="search_btm"></div>');
					prop13 = '';
				} else {
					var startnum = ((TBS.VideosPerPage * Search.currentPage) - TBS.VideosPerPage),
					    endnum = startnum + data.videos.length;
					startnum = (startnum + 1);

					$("#search").append('<div id="search_tp"></div><div id="overlay"><h1>search results</h1><h2>results ' + startnum + '-' + endnum + ' of ' + data.total + ' for ' + $("#search_videos").attr("value") + '</h2><p id="close"><a href="#">x<span></span></a></p><div class="paginate top"></div><div id="shows" class="customScroll"></div><div class="paginate bottom"></div></div><div id="search_btm"></div>');

					$.each(data.videos, function(i, item) {
						$("#search #shows").append('<div class="show"><ul class="options"><li><a href="' + item.url + '" class="play" title="play">PLAY<span></span></a></li><li><a href="' + item.url + '" class="add" title="add to playlist">ADD<span></span></a></li></ul><a href="' + item.url + '" class="play"><img src="' + item.thumbnailpath + '" width="96" height="72" alt="" /></a><h4>' + item.episodetitle + '</h4><p>' + item.clipdescription + '</p><input type="hidden" class="episodetitle" value="' + item.episodetitle + '"><input type="hidden" class="contentid" value="' + item.contentid + '"></div>');
					});

					if (expanded) {
						var nodes = ["#search #search_tp", "#search #close", "#search #search_btm", "#content > *:not(#search)", "#subnav", "#playlist"];
						for (var i = 0, j = nodes.length; i < j; i++) {
							$(nodes[i]).remove();
						}
						$('#main').removeClass('search-overlayed').removeClass('playlist-overlayed');
						$("#search #overlay").remove().children().appendTo("#search");
						$("#search .show .options a span").remove();
						$("#search").removeClass("transition").addClass("search-expanded").width(532).css("paddingLeft", 19);
						$("#search .friend .group").css("marginRight", 2);
						$("#search div.collapsed .episode").css("marginRight", 12);
						if (!$.browser.msie) {
							$('#search .customScroll').css('paddingRight', 15);
						}
					}

					var pages = Math.ceil(parseInt(data.total, 10) / TBS.VideosPerPage),
					    currentPage = Search.currentPage, nextPage, prevPage,
					    url = TBS.SearchInfo;

					if (pages > 1) {

						prevPage = (currentPage - 1);
						nextPage = (currentPage + 1);

						if (prevPage > 0) {
							$('<a href="' + url + '?page=' + prevPage + '" rel="/">&lt; prev</a>').prependTo("#search .paginate");
						}
						if (nextPage < (pages + 1)) {
							$('<a href="' + url + '?page=' + nextPage + '" rel="/">next &gt;</a>').appendTo("#search .paginate");
						} else {
							$('<a href="#" class="hide"></a>').appendTo("#search .paginate");
						}

						for (i = 0, j = pages; i < j; i++) {
							var active = ((i + 1) == currentPage) ? 'active' : 'alt';
							$('<a href="' + url + '?page=' + (i + 1) + '" rel="/" class="' + active + '">' + (i + 1) + '</a>').insertBefore("#search .paginate a:last-child");
							if ((i + 1) != pages) {
								$('<span class="alt">|</span>').insertBefore("#search .paginate a:last-child");
							}
						}
					}

					$('#search .paginate a').bind("click", function(e) {
						if (!$(this).hasClass("active")) {
							_this.render(_this.href(this));
							Search.currentPage = parseInt($(this).attr("href").split("?")[1].split("page=")[1], 10);
						}
						e.preventDefault();
					});
				}

				if (Search.doOnce) {
					Search.doOnce = false;
					$("#search").hide();
					_this.toggle();
					_this.fix("#search_tp");
					_this.fix("#search_btm");
				}

				$("#search #close").bind("click", function(e) {
					Search.currentPage = null;
					_this.toggle(e);
					e.preventDefault();
				});
				$("#search #shows .options .add").bind("click", function(e) {
					var cookie = Playlist.cookie($(this), "add");
					if (cookie) {
						var empty = document.getElementById("error_share_empty");
						if (empty) {
							empty.parentNode.removeChild(empty);
						}
						var foo = $(this).parents(".show").clone(true).appendTo("#playlist #shows .me");
						var bar = ($(foo).find(".options li:first-child"));
						$('<li><a href="' + $(this).attr('href') + '" class="delete">DELETE</a></li>').insertAfter($(bar));
						$('<li><a href="#" class="up">MOVE UP</a></li><li><a href="#" class="down">MOVE DOWN</a></li>').insertBefore($(bar));
						$(foo).find(".options li a span").remove();
						($(foo).find(".options li:last-child")).remove();
						Playlist.options();
					}
					e.preventDefault();
				});
				$("#search #shows .play").bind("click", function(e) {
					_this.play(this, data);
					e.preventDefault();
				});

				if (expanded) {
					$("#search #shows .play").unbind("click", _this.doWiden);
				} else {
					$("#search #shows .play").bind("click", {
						self: _this
					}, _this.doWiden);
				}

				/* Prettify scrollbars */
				$('#search .customScroll').jScrollPane(Scroll.options);
				$('#search .jScrollPaneContainer').css('width','auto');
				$('#search .jScrollPaneTrack').css('right','10px');
				$('#search .customScroll').css('width', 'auto');
				if($.browser.msie) {
					$('#search .customScroll').css('paddingRight', 15);
				}
			}
		});
		TBS.TrackOmniture({channel:"Videos", page:"Videos:Search Results", server:"Search", prop13:prop13, prop14:$("#search_videos").attr("value"), prop15:"Video Player", prop16: "Videos:Search"});
	},
	toggle : function(e, b) {

		/* Call Overlay */
		Overlay.hide();

		$('#main').removeClass('search-overlayed').removeClass('playlist-overlayed');
		$('.search-expanded').removeClass('search-expanded');
		var content = "#search",
		    _this = this;

		Search.trig = (Search.trig) ? false : true;

		if (Playlist.trig) {
			$("div[id^=playlist]").remove();
			Playlist.trig = false;
			$("#nav-my-playlist a").one("click", function() {
				Playlist.init();
			});
		}

		if (!($.browser.safari) && !($.browser.msie)) {
			$("#search #shows").css("overflow", "hidden");
		} else if ($.browser.msie) {
			$("#search #shows").css("overflow-x", "hidden");
		}
		if (Search.trig) {
			$("#header ul .active").removeClass("active").addClass("inactive");
			$("#main").addClass("search-overlayed");
		}
		if (!$("#search_bg")[0]) {
			$('<div id="search_bg"></div>').appendTo($(content).parent()).css({
				"opacity": 0.8,
				"width" : $(content).parent().width()
			}).toggle().fadeIn();
		} else {
			if (Search.trig) {
				$("#search_bg").fadeIn();
			}
		}
		if ($("#playlist.playlist-expanded")[0]) {
			$("#search").css("z-index", 400);
			$("#search_bg").css("z-index", 300);
			$("#playlist").css("z-index", 200);
			$("#playlist_bg").css("z-index", 100);
		}
		$("#search_bg").one("click", function(e) {
			if (Search.trig) {
				_this.toggle(e);
			}
		});
		$(content).css({
			top : 63,
			right : 28,
			width : 426
		}).slideToggle(600, function() {
			$("#search #shows").css("overflow", "");
			if (!Search.trig && !Playlist.trig) {
				$("#search_bg").fadeOut(function() {
					$("#search").remove();
				});
				$("#header ul .inactive:first").removeClass("inactive").addClass("active");
			}
		});
	},
	fix : function(e) {
		var width;
		if ($.browser.msie) {
			width = $("#search").css("width");
		} else {
			width = $(e).css("width");
		}
		$(e).width(parseInt(width, 10));
	},
	doWiden : function(e) {
		var _this = e ? e.data.self : this;
		_this.widen();
	},
	widen : function() {
		var _this = Search.prototype,
		    content = "#search",
		    nodes = ["#search #search_tp", "#search #close", "#search #search_btm", "#content > *:not(#search)", "#subnav", "#playlist"];
		$("#pagination").remove();
		$("#search .paginate:first").wrap('<div id="pagination"></div>');
		$("#search_bg").fadeOut();
		$("#main").toggleClass("search-expanded");
		var m = 69;
		$("#search .show .options").css({
			marginLeft : -(m)
		});
		$(content).addClass("transition");
		$(content).animate({
			width: 570
		}, {
			duration: 400,
			complete: function() {
				for (var i = 0, j = nodes.length; i < j; i++) {
					$(nodes[i]).remove();
				}
				_this.expand();
				Search.trig = false;
			}
		});
		$("#search #shows .play").unbind("click", _this.doWiden);
		return false;
	},
	expand : function() {
		$('#featured').remove();
		$('#main').removeClass('search-overlayed').removeClass('playlist-overlayed');
		$("#search #overlay").remove().children().appendTo("#search");
		$("#search .show .options a span").remove();
		$("#search").removeClass("transition").addClass("search-expanded").width(532).css("paddingLeft", 19);
		$("#search .friend .group").css("marginRight", 2);
		$("#search div.collapsed .episode").css("marginRight", 12);
		if (!$.browser.msie) {
			$('#search .customScroll').css('paddingRight', 15);
		}

		var m = 69, start, to;
		$("#search .show .options").css({
			marginLeft : -m
		}).animate({
			marginLeft : 0
		}, {
			queue: false,
			duration: 150
		});
		start = 108;
		to = start + m;
		$("#search .show p").css({
			marginLeft : start
		}).animate({
			marginLeft : to
		}, {
			queue: false,
			duration: 150
		});
		start = 135/*@cc_on+10@*/;
		to = start + m;
		$("#search .show h4").css({
			marginLeft : start
		}).animate({
			marginLeft : to
		}, {
			queue: false,
			duration: 150
		});
		Search.expanded = true;
		$("#header li").removeClass("active");

	},
	play : function(e, data) {
		TBS.Video = [data];

		/* User has explicitly triggered this video to play */
		/* Stop the current video from playing (if any) */
		TBS.Stop();

		/* Trigger chosen video to play */
		TBS.Play($(e).attr("href"));
	}
};

/**
 * @author Richard Herrera
 * @constructor Playlist
 *
 * The Playlist object handles anything attributed to "My Playlist",
 * including cookie management and shared playlist manipulation.
 */
$(document).ready(function() {
	Playlist.init();
	Playlist.update($.cookieJar("My-TBS-Playlist").get("myPlaylist"));
});
var Playlist = {
	init : function() {
		var _this = this;
		if ($("#nav-my-playlist").hasClass("active")) {
			return;
		}
		$("#header ul .inactive").removeClass("inactive").addClass("active");
		$("#nav-my-playlist").one("click", function(e) {
			_this.load();
			e.preventDefault();
		});
	},
	load : function(e) {
		var _this = this;

		/* Call Overlay */
		Overlay.show();

		var dir = TBS.Directory;

		var chip = $.cookieJar("My-TBS-Playlist"),
		    me = chip.get("myPlaylist"),
		    them = chip.get("sharedPlaylists");

		var MyPlaylist = [],
		    TheirPlaylist = [],
		    count, objects;

		_this.empty = function() {
			$('<div id="error_share_empty" class="message"><p>You do not have any videos in your playlist</p><img src="http://i.cdn.turner.com/v5cache/TBS/video/img/cmn/playlist/empty.png" alt="Empty" class="empty" /><p>Select the \'add to playlist\' icon next to a video to add it to your playlist.</p><p><a href="#"><img src="http://i.cdn.turner.com/v5cache/TBS/video/img/cmn/playlist/btn_close.png" alt="Close" class="close" /></a></p></div>').appendTo("#playlist #shows .me");
			$("#playlist .close").bind("click", function(e) {
				_this.toggle(e);
				$("#nav-my-playlist a").one("click", _this.toggle);
				e.preventDefault();
			});
		};

		_this.handle = function() {

			var count = me ? me.length : 0;

			$('<div id="playlist"><div id="playlist_tp"></div><div id="overlay"><h1>my playlist <em>[' + count + ']</em></h1><p id="close"><a href="#">x<span></span></a></p><form id="share_playlist" method="post" action="' + TBS.SharePlaylistSubmission + '" class="validate"><fieldset><legend>share your playlist</legend><dl><dt><label for="your_name">your name:</label></dt><dd><input type="text" name="your_name" id="your_name" size="40" maxlength="40" class="text required" /></dd><dt><label for="your_email">your email:</label></dt><dd><input type="text" name="your_email" id="your_email" size="40" maxlength="60" class="text required" /></dd><dt><label for="friends_emails">friends&lsquo;s emails [separate multiple emails with commas]:</label></dt><dd><textarea rows="4" cols="39" name="friends_emails" id="friends_emails" class="required"></textarea></dd></dl><div id="buttons"><input type="image" src="http://i.cdn.turner.com/v5cache/TBS/video/img/cmn/playlist/btn_cancel.png" alt="Cancel" /><input type="image" src="http://i.cdn.turner.com/v5cache/TBS/video/img/cmn/playlist/btn_submit.png" alt="Submit" /><a href="http://www.tbs.com/general/privacy/" class="popup">privacy policy</a></div></fieldset></form><div id="shows" class="customScroll"><div class="me"></div></div></div><div id="playlist_btm"></div></div>').appendTo("#main").toggle();

			$('<ul class="actions"><li><a href="#" id="clear">clear list<span></span></a></li><li><a href="#" id="share">share list<span></span></a></li></ul>').insertBefore("#playlist #shows");
			$.each(MyPlaylist, function(i, item) {
				$.each(item.videos, function(j, mine) {
					$('<div class="show"><ul class="options"><li><a href="#" class="up" title="move item up">MOVE UP<span></span></a></li><li><a href="#" class="down" title="move item down">MOVE DOWN<span></span></a></li><li><a href="' + mine.url + '" class="play" title="play">PLAY<span></span></a></li><li><a href="' + mine.url + '" class="delete" title="remove from playlist">DELETE<span></span></a></li></ul><a href="' + mine.url + '" class="play"><img src="' + mine.thumbnailpath + '" width="96" height="72" alt="" /></a><h3>' + mine.episodetitle + '</h3><p>' + mine.clipdescription + '</p><input type="hidden" class="episodetitle" value="' + mine.episodetitle + '"><input type="hidden" class="contentid" value="' + mine.contentid + '"></div>').appendTo("#playlist #shows .me");
				});
			});

			if (!me || !me[0]) {
				_this.empty();
			}

			if (them) {
				$.each(TheirPlaylist, function(i, item) {
					$('<div class="friend collapsed" rel="index_' + i + '"><div class="episode"><ul class="options"><li><a href="#" class="up">MOVE UP<span></span></a></li><li><a href="#" class="down">MOVE DOWN<span></span></a></li></ul><h2>videos from ' + unescape(item.from) + ' [' + item.videos[0].total + ']</h2><ul class="actions"><li><a href="#" class="merge">merge lists<span></span></a></li><li><a href="#" class="delete">delete list<span></span></a></li></ul></div><div class="group"></div><div class="friend_btm"></div></div>').insertBefore("#playlist #shows .me");
					$.each(item.videos[0].videos, function(j, their) {
						var target = $("#playlist #shows .friend");
						target = $(target[target.length -1]);
						$('<div class="show"><ul class="options"><li><a href="#" class="up" title="move item up">MOVE UP<span></span></a></li><li><a href="#" class="down" title="move item down">MOVE DOWN<span></span></a></li><li><a href="' + their.url + '" class="play" title="play">PLAY<span></span></a></li><li><a href="' + their.url + '" class="delete" title="remove from playlist">DELETE<span></span></a></li></ul><img src="' + their.thumbnailpath + '" width="96" height="72" alt="" /><h3>' + their.episodetitle + '</h3><p>' + their.clipdescription + '</p><input type="hidden" class="episodetitle" value="' + their.episodetitle + '"><input type="hidden" class="contentid" value="' + their.contentid + '"></div>').appendTo(target.children(".group"));
					});
				});
			}

			/* PLAYLIST SHARE FORM */
			$("#share_playlist").valdiation = new Validate();
			$("#share_playlist").hide();

			if (Search.trig) {
				Search.prototype.toggle();
			}
			_this.toggle();


			/* Prettify scrollbars */
			$('.customScroll').jScrollPane(Scroll.options);
			$('.franchise .customScroll').jScrollPane(Scroll.animate);


			_this.fix("#playlist_tp");
			_this.fix("#playlist_btm");


			$("#playlist #close").bind("click", function(e) {
				_this.toggle(e);
				$("#nav-my-playlist a").one("click", _this.toggle);
				$('.customScroll').jScrollPane(Scroll.options);
				e.preventDefault();
			});
			$("#share").bind("click", function(e) {
				$(this).parent().parent().slideToggle(400, function() {
					$("#share_playlist").slideToggle(600, function() {
						$(this).css('visibility','visible');
					});
					$('.customScroll').jScrollPane(Scroll.options);
				});
				e.preventDefault();
			});
			$('#share_playlist #buttons input[alt="Cancel"]').bind("click", function(e) {
				$("#share_playlist").slideToggle(600, function() {
					$("#share").parent().parent().slideToggle(400);
				}).css({
					'visibility': 'hidden'
				});
				$('.customScroll').jScrollPane(Scroll.options);
				e.preventDefault();
			});

			/* SUBMISSION BEHAIVOUR */

			$('#share_playlist').bind("submit", function(e) {
				e.preventDefault();
				var _form = this;
				if (_form.allowSubmit) {
					var inputs = [];
					$(':input', this).each(function() {
					    inputs.push(this.name + '=' + escape(this.value));
					});

					/* create the message div if it doesn't exist. */
					if (!_form.messageContainer) {
						_form.messageContainer = $('<div id="share_playlist_result" class="message"></div>');
						$(_form).after(_form.messageContainer);
						_form.messageContainer.populate = function(response) {
							$(_form).fadeOut(400,function(){
								$(_form.messageContainer).html(response);
								$(_form.messageContainer).show();
								$("#share_playlist_result img.close").parent().bind("click", function(e){
									$(_form.messageContainer).hide(function(){
										$("#share").parent().parent().slideToggle(400);
									});
									e.preventDefault();
								});

								/* Clear the fields */
								$("#" + _form.id + " input[@type=text], #" + _form.id + " textarea").each(function(i){
									this.value = "";
								});
							});
						};
					}

					TBS.TrackOmniture({prop16:"Videos:Share Playlist"});

					$.ajax({
						url : _form.action,
						data: inputs.join('&'),
						dataType : 'html',
						cache : false,
						error : function(req) {
							var msg = (req.readyState !== 4) ? "incomplete request" : req.statusText;
							_form.messageContainer.populate('<h3>Whoops!</h3><p>There was an error - "' + msg + '" - sending your request.  Please try again later.</p><p><a href="#"><img src="http://i.cdn.turner.com/v5cache/TBS/video/img/cmn/playlist/btn_close.png" alt="Close" class="close" /></a></p>');
						},
						success : function(html){
							_form.messageContainer.populate(html);
						}
					});
				}
			});

			/* OPTIONS */
			_this.options();

			/* ACTIONS */
			_this.actions();

			if (e) {
				_this.doWiden();
				if (Playlist.mine) {
					TBS.Video = Playlist.mine;
					_this.play();
				}
			}

			$("#playlist .friend .episodenum .up").bind("click", function(e) {
				_this.move(this);
				e.preventDefault();
			});
			$("#playlist .friend .episodenum .down").bind("click", function(e) {
				_this.move(this);
				e.preventDefault();
			});

			var clickToToggle = function() {
				var _this = $(this).parents(".friend")[0];
				var clickToExpand = function() {
					_this.pre_height = $(_this).height();
					$(_this).removeClass("collapsed").addClass("active");
					_this.post_height = $(_this).height();
					$(_this).height(_this.pre_height).animate({
						height : _this.post_height
					}, {
						complete : function() {
							$(_this).height("auto");
							$('.jScrollPaneContainer').each(function() {
								if(this.scrollHeight > this.offsetHeight) {
								 $(this).find('.customScroll').jScrollPane(Scroll.options);
								}
							});
						}
					});
				};
				var clickToCollapse = function() {
					var _this = $(this).parents(".friend")[0];
					$(_this).animate({
						height : _this.pre_height
					}, {
						complete : function() {
							$(_this).removeClass("active").addClass("collapsed");
							$('.jScrollPaneContainer').each(function() {
								if(this.scrollHeight > this.offsetHeight) {
								 $(this).find('.customScroll').jScrollPane(Scroll.options);
								}
							});
						}
					});
				};
				if(/collapsed/.test(_this.className)) {
					clickToExpand.call(this);
				} else if(/active/.test(_this.className)) {
					clickToCollapse.call(this);
				}
			}

			$("#playlist .friend.collapsed h2").bind("click", clickToToggle);

		};

		_this.friend = function() {
			if (them && them[0]) {
				var count = 0;
				$.each(them, function(i, item) {
					var TheirArray = {
						"from": item.from,
						"videos": []
					};
					$.getJSON(TBS.PlaylistInfo + (item.videos.join(",")), function(feed) {
						TheirArray.videos.push(feed);
						TheirPlaylist.push(TheirArray);
						count++;

						if (count == them.length) {
							_this.handle();
						}
					});

				});
				Playlist.theirs = TheirPlaylist;
			} else {
				_this.handle();
			}
		};

		var tabs = new Tabs();

		if (me && me[0]) {
			$.getJSON(TBS.PlaylistInfo + (me.join(",")), function(feed) {
				MyPlaylist.push(feed);
				Playlist.mine = MyPlaylist;
				_this.friend();
			});
		} else {
			_this.friend();
		}

	},
	options : function() {
		var _this = this;
		$("#playlist #shows .options .up").bind("click", function(e) {
			e.preventDefault();
			var kids = $(this).parents(".friend").children(".group").children(),
			    son = $(this).parents(".show")[0];

			if (son != kids[0]) {
				$(this).parents(".show").insertBefore($(this).parents(".show").prev());
			}
		});
		$("#playlist #shows .options .down").bind("click", function(e) {
			e.preventDefault();
			var dad = $(this).parents(".friend").children(".group"),
			    kids = $(this).parents(".friend").children(".group").children(),
			    son = $(this).parents(".show")[0];

			if (son == kids[kids.length - 1]) {
				/* For some reason jQuery won't remove this element */
				var empty = document.getElementById("error_share_empty");
				if (empty) {
					empty.parentNode.removeChild(empty);
				}
				$(this).parents(".show").prependTo($(this).parents(".friend").siblings(".me"));

				_this.cookie($(this).parent().siblings().children("a.play"), "add");
			} else {
				$(this).parents(".show").insertAfter($(this).parents(".show").next());
			}
			if (dad[0] && !dad.children()[0]) {
				_this.remove(dad);
			}
		});
		$("#playlist #shows .play").bind("click", {self: _this}, _this.doWiden);

		Playlist.options.assignVideo = function(e) {
			var i = parseInt($(this).parents(".friend").attr("rel").split("index_")[1]);
			TBS.Video = [{
				"videos" : Playlist.theirs[i].videos[0].videos
			}];
			Playlist.play(this, true);
			e.preventDefault();
		};
		$("#playlist #shows .friend .play").bind("click", Playlist.options.assignVideo);
		$("#playlist #shows .me .play").bind("click", function(e) {
			TBS.Video = Playlist.mine;
			Playlist.play(this, true);
			e.preventDefault();
		});
		$("#playlist #shows .options .delete").unbind();
		$("#playlist #shows .options .delete").bind("click", function(e) {
			e.preventDefault();
			episodetitle = $(this).parents(".show").children(".episodetitle").attr("value");
			contentid = $(this).parents(".show").children(".contentid").attr("value");
			$(this).parents(".show").remove();
			_this.cookie($(this).parents("ul").find("a.play"), "del");
			$('.customScroll').jScrollPane(Scroll.options);

			TBS.TrackOmniture({eVar2:episodetitle + ":(" + contentid + ")", events:"event9"});
		});


		$("#playlist .friend .episode > .options .up").bind("click", function(e) {
			$(this).parents(".friend").insertBefore($(this).parents(".friend").prev());
			e.preventDefault();
		});
		$("#playlist .friend .episode > .options .down").bind("click", function(e) {
			$(this).parents(".friend").insertAfter($(this).parents(".friend").next());
			e.preventDefault();
		});

	},
	actions : function() {
		var _this = this;
		$("#playlist .friend .actions .merge").bind("click", function(e) {
			$(this).parents(".friend").find(".play").unbind("click", Playlist.options.assignVideo);
			$(this).parents(".friend").find(".options a.play").bind("click", function(e) {
				TBS.Video = Playlist.mine;
				Playlist.play(this, true);
				e.preventDefault();
			});
			$(this).parents(".friend").children(".group").children().prependTo($(this).parents(".friend").siblings(".me"));
			_this.merge($(this).parents(".friend").children(".group"));
			e.preventDefault();
		});
		$("#playlist .friend .actions .delete").bind("click", function(e) {
			_this.remove($(this).parents(".friend").children(".group"));
			e.preventDefault();
		});
		$("#playlist .actions #clear").bind("click", function(e) {
			var clr = confirm("Are you sure you want to clear your playlist?");
			if(clr) {
				_this.remove("all");
				$('.customScroll').jScrollPane(Scroll.options);
				e.preventDefault();

				TBS.TrackOmniture({eVar2:"Videos:Clear Playlist"});
			}
		});
	},
	doWiden : function(e) {
		if(e) {
			e.preventDefault();
		}
		var _this = e ? e.data.self : this;
		_this.widen();
	},
	widen : function() {
		var _this = this;
		var content = "#playlist";
		$("#playlist_bg").fadeOut();
		$("#main").toggleClass("playlist-expanded");
		$(content).addClass("transition");

		$(content).animate({
			width: 570
		}, {
			duration: 400,
			complete: function() {
				var nodes = ["#playlist #playlist_tp", "#playlist #close", "#playlist #playlist_btm", "#content > *:not(#playlist)", "#subnav", "#search"];
				$.each(nodes, function(i, node) {
					$(node).remove();
				});
				_this.expand();
				Playlist.trig = false;
			}
		});
		$("#nav-my-playlist a").unbind("click", _this.toggle);
		$("#playlist #shows .play").unbind("click", _this.doWiden);

		return false;
	},
	toggle : function(e, b) {
		/* Call Overlay */
		Overlay.hide();

		$('#main').removeClass('search-overlayed').removeClass('playlist-overlayed');
		$('.playlist-expanded').removeClass('playlist-expanded');
		var content = "#playlist",
		    _this = this;

		Playlist.trig = (Playlist.trig) ? false : true;

		if (Playlist.trig) {
			TBS.TrackOmniture({channel:"Videos", page:"Videos:My Playlist", server:"Browse"});
		}

		if ($("div[id^=search]:not(.search-expanded)")[0]) {
			$("div[id^=search]:not(.search-expanded)").remove();
			Search.trig = false;
		}

		if (!($.browser.safari) && !($.browser.msie)) {
			$("#playlist #shows").css("overflow", "hidden");
		} else if ($.browser.msie) {
			$("#playlist #shows").css("overflow-x", "hidden");
		}
		$(content).css({paddingRight: 20});

		if ($.browser.msie && $.browser.version != "7.0") {
			$("#playlist #shows").css("height", "");
		}

		$("#search_bg").fadeOut();
		if (Playlist.trig) {
			$("#header ul .active").removeClass("active").addClass("inactive");
			$("#nav-my-playlist").addClass("active");
			$("#main").addClass("playlist-overlayed");
		}
		if (!$("#playlist_bg")[0]) {
			$('<div id="playlist_bg"></div>').appendTo($(content).parent()).css({
				"opacity": 0.8,
				"width" : $(content).parent().width()
			}).toggle().fadeIn();
		} else {
			if (Playlist.trig) {
				$("#playlist_bg").fadeIn();
			}
		}
		if ($("#search.search-expanded")[0]) {
			$("#playlist").css("z-index", 400);
			$("#playlist_bg").css("z-index", 300);
			$("#search").css("z-index", 200);
			$("#search_bg").css("z-index", 100);
		}
		$("#playlist_bg").one("click", function(e) {
			if (Playlist.trig) {
				_this.toggle(e);
				$("#nav-my-playlist a").one("click", _this.toggle);
			}
		});
		$(content).slideToggle(600, function() {
			$("#playlist #shows").css({
				"overflow": "",
				"height" : "auto"
			});
			if ($.browser.msie && $.browser.msie != "7.0") {
				$("#playlist #shows").css("height", "");
			}
			$(content).css({
				paddingRight: 0
			});


			/* Prettify scrollbars */
			if ($('playlist .customScroll')[0]) {
				$('#playlist .customScroll').jScrollPane(Scroll.options);
			}
			$('#playlist .jScrollPaneContainer').css('width','auto');
			$('#playlist .jScrollPaneTrack').css('right','20px');
			$('#playlist .customScroll').css({
				width : 'auto',
				paddingRight : '5px'
			});

			if (!Playlist.trig) {
				$("#playlist_bg").fadeOut();
				$("#nav-my-playlist").removeClass("active");
				$("#header ul .inactive:not(#nav-my-playlist)").removeClass("inactive").addClass("active");
			}
		});
	},
	fix : function(e) {
		var width;
		if ($.browser.msie) {
			width = $("#playlist").width();
		} else {
			width = $(e).width();
		}
		$(e).width(parseInt(width, 10));
	},
	expand : function() {
		var _this = this;
		$('#featured').remove();
		$('#main').removeClass('search-overlayed').removeClass('playlist-overlayed');
		$("#playlist #overlay").remove().children().appendTo("#playlist");
		$("#playlist .show .options a span, #playlist #overlay_tp, #playlist #overlay_btm").remove();
		$("#playlist").removeClass("transition").addClass("playlist-expanded").width(532).css("paddingLeft", 19);
		//$("#playlist .friend .group").css("marginRight", 2);
		//$("#playlist div.collapsed .episode").css("marginRight", 12);
		$('#playlist .customScroll').css('marginRight', 12).width('auto');

		var m = 69, start, to;
		$("#playlist .show .options").css({
			marginLeft : -m
		}).animate({
			marginLeft : 0
		}, {
			queue: false,
			duration: 150
		});
		start = 108;
		to = start + m;
		$("#playlist .show p").css({
			marginLeft : start
		}).animate({
			marginLeft : to
		}, {
			queue: false,
			duration: 150
		});
		start = 135/*@cc_on+10@*/;
		to = start + m;
		$("#playlist .show h3").css({
			marginLeft : start
		}).animate({
			marginLeft : to
		}, {
			queue: false,
			duration: 150,
			complete: function() {
				if($.browser.msie) {
					$("#playlist").css('left', 0);
				}
			}
		});
		StateManager.setState($("#nav-my-playlist a").attr("rel"));
		$("#header .inactive").removeClass("inactive");
		Playlist.expanded = true;
	},
	play : function(e, f) {
		if (TBS.newpage && !f) {
			TBS.Video = [window[TBS.JSON_ID]];
			TBS.newpage = false;
		}

		if (e) {
			e = $(e).attr("href");
		} else if (TBS.Video) {
			e = TBS.Video[0].videos[0].url;
		}
		if (e) {

			/* User has explicitly triggered this video to play */
			/* Stop the current video from playing (if any) */
			TBS.Stop();

			/* Trigger chosen video to play */
			TBS.Play(e);
		}
	},
	move : function(e) {
		var _this = this,
		    dir = $(e).attr("class");
		dir = (dir == "up") ? "prev" : "next";
		var parent = $(e).parents(".friend"),
		    sibling = parent[dir]()[0];
		if (sibling) {
			if (dir == "prev") {
				parent.insertBefore(sibling);
			} else {
				parent.insertAfter(sibling);
			}
		}
	},
	remove : function(e) {
		var _this = this;
		if (e == "all") {
			$.cookieJar("My-TBS-Playlist").set("myPlaylist", []);
			$.cookieJar("My-TBS-Playlist").set("sharedPlaylists", []);
			$("#playlist #shows").children().empty();
			_this.update([]);
			return;
		}

		var mP = $.cookieJar("My-TBS-Playlist").get("myPlaylist"),
		    sP = $.cookieJar("My-TBS-Playlist").get("sharedPlaylists"),
		    h2 = e.prev(".episode").children("h2").text().split(("videos from ").toLowerCase())[1].split(" [")[0];
		var keepShare = [];
		for (var i = 0, j = sP.length; i < j; i++) {
			if (sP[i]["from"] != h2) {
				keepShare.push(sP[i]);
			}
		}
		$.cookieJar("My-TBS-Playlist").set("sharedPlaylists", keepShare);
		e.parent().remove();
	},
	merge : function(e) {
		var _this = this;
		_this.limit = _this.limit || 25;

		var mP = $.cookieJar("My-TBS-Playlist").get("myPlaylist"),
		    sP = $.cookieJar("My-TBS-Playlist").get("sharedPlaylists"),
		    h2 = e.prev(".episode").find("h2").text().toLowerCase().split(("videos from "))[1].split(" [")[0];
		var merge, i, j, newShare = [];
		if (sP.length > 0) {
			for (i = 0, j = sP.length; i < j; i++) {
				if (sP[i]["from"].toLowerCase() == h2) {
					merge = sP[i];
				} else {
					newShare.push(sP[i]);
				}
			}
		}

		if (merge) {

			mP = mP || [];

			for (i = 0, j = merge.videos.length; i < j; i++) {
				var exists = true;
				if (mP.length > 0) {
					for (var k = 0, l = mP.length; k < l; k++) {
						if (mP[k] == merge.videos[i]) {
							exists = false;
						}
					}
				}
				if (exists && mP.length < _this.limit) {
					mP.push(merge.videos[i]);
				} else if (mP.length >= _this.limit) {
					_this.full();
					break;
				}
			}
		}

		// Reset playlist, cause we've merged
		var resetPlaylist = [];
		$.getJSON(TBS.PlaylistInfo + (mP.join(",")), function(feed) {
			resetPlaylist.push(feed);
			Playlist.mine = resetPlaylist;
		});

		$.cookieJar("My-TBS-Playlist").set("myPlaylist", mP);
		$.cookieJar("My-TBS-Playlist").set("sharedPlaylists", newShare);
		e.parent().remove();
		$("#playlist #error_share_empty").remove();
		_this.update(mP);
	},
	cookie : function(e, act) {
		var _this = this;
		_this.limit = _this.limit || 25;

		var chip = $.cookieJar("My-TBS-Playlist"),
		    seed = $(e).parents(".show"),
		    id = $(e).attr("href").split(/\||\,/g);

		var i, j, k, l;
		for (i = 0, j = id.length; i < j; i++) {
			var item = id[i];
			var num = parseInt(item, 10).toString();
			if (num != "NaN") {
				if (num.split("").length > 3) {
					id = item;
					break;
				}
			}
		}

		/* get the name from the cookieJar */
		var myPlaylist = chip.get("myPlaylist"),
		    sharedPlaylists = chip.get("sharedPlaylists");
		myPlaylist = myPlaylist || [];
		sharedPlaylists = sharedPlaylists || [];

		if (act == "del") {

			if ($("#playlist .friend.active")[0] && !$("#playlist .friend.active .group").children(".show")[0]) {
				var text = $("#playlist .friend.active h2").text();
				text = text.split("videos from ")[1].split(" [")[0];
				for (i = 0, j = sharedPlaylists.length; i < j; i++) {
					if (sharedPlaylists[i].from == text) {
						sharedPlaylists.splice(i, 1);
						break;
					}
				}
				$("#playlist .friend.active").remove();
			}

			var newPlaylist = [];
			for (i = 0, j = myPlaylist.length; i < j; i++) {
				if (myPlaylist[i] != id) {
					newPlaylist.push(myPlaylist[i]);
				}
			}
			myPlaylist = newPlaylist;
		} else if (act == "add") {
			if (myPlaylist.length < _this.limit) {
				var exists = true;
				for (i = 0, j = myPlaylist.length; i < j; i++) {
					if (myPlaylist[i] == id) {
						exists = false;
					}
				}
				if (exists) {
					myPlaylist.push(id);
				}
			} else {
				_this.full();
			}
		}
		for (i = 0, j = sharedPlaylists.length; i < j; i++) {
			var share = sharedPlaylists[i].videos,
			    newShare = [];

			for (k = 0, l = share.length; k < l; k++) {
				if (share[k] != id) {
					newShare.push(share[k]);
				}
			}
			sharedPlaylists[i].videos = newShare;
		}
		chip.set("myPlaylist", myPlaylist);
		chip.set("sharedPlaylists", sharedPlaylists);
		_this.update(myPlaylist);
		if (act == "add") {
			if (exists) {
				return true;
			} else {
				return false;
			}
		}
	},
	full : function() {
		/* Your playlist is full, 25 only */
		return;
	},
	update : function(e) {
		var _this = this;
		var text = $("#nav-my-playlist a").text();

		/* Check if My Playlist is undefined (BH added) */
		if (!e) {
			e = "";
		}

		if (typeof e == "object" && !e[0] && _this.empty && !$("#playlist #error_share_empty")[0]) {
			_this.empty();
		}

		text = text.replace(/\[(\d*)\]/m, "[" + e.length + "]");
		$("#nav-my-playlist a").text(text);
		$("#playlist h1 em").text("[" + e.length + "]");
	}
};
Playlist.assemble = function(e) {
	var chip = $.cookieJar("My-TBS-Playlist"),
	    h2 = $(e).parents(".friend").find("h2").text().split(("videos from ").toLowerCase())[1].split(" [")[0],
	    vids = [];
	$(e).each(function(i) {
		vids.push($(this).attr("href").split(/\||\,/g)[0]);
	});
	var myPlaylist = chip.get("myPlaylist") ||[],
	    sharedPlaylists = chip.get("sharedPlaylists") || [];
	var exists = true;
	for (var i = 0, j = sharedPlaylists.length; i < j; i++) {
		if (sharedPlaylists[i].from == h2) {
			exists = false;
		}
	}

	if (exists) {
		sharedPlaylists.push({"from" : h2, "videos" : vids});
		$.cookieJar("My-TBS-Playlist").set("sharedPlaylists", sharedPlaylists);
	}
};

/**
 * @author David Zuch
 * @constructor Showlist
 */
var Showlist = function(el, shows) {
	this.el = el;
	this.shows = shows;
	this.init();
};
Showlist.prototype = {
	init : function() {
		var _this = this;
		/* attach event handlers */
		$(this.shows).mouseover(function(e) {
			_this.expand(this);
		}).bind("click", function() {
			Page.load($(this).children("h2").children("a"));
		}).children("h2").children("a").bind("click", function(e) {
			e.preventDefault();
		});
	},
	expand : function(el) {
		/* expand the show item on hover */
		/* checks to make sure we should be expanding the current element */
		if(el.timer) {
			clearTimeout(el.timer);
		}
		if(el.expanding || el.expanded) {
			return;
		}
		if(el.contracting) {
			$(el).stop();
			el.contracting = false;
		}
		el.expanding = true;

		/* Go through a series of steps to animate the desired expanding effect */
		$(el).css({
			'background-image': 'none',
			'background-color': '#6BC6E9'
		}).children('h2').css({
			'background-image': 'none'
		});
		el.bgStep = 1;
		var p = $.browser.msie ? 'css' : 'animate';
		$(el)[p]({
			backgroundColor: '#F37B21'
		}, {
			queue: false,
			duration: 100,
			step: function() {
				el.bgStep = 2;
			},
			complete: function() {
				$(el).css({'background': 'transparent url(http://i.cdn.turner.com/v5cache/TBS/video/img/cmn/browse/bg_show_a.png) no-repeat center'});
				el.bgStep = 3;
			}
		}).animate({
			height: 99,
			paddingTop: 6,
			paddingBottom: 6,
			paddingLeft: 16,
			paddingRight: 16,
			marginLeft: 0
		}, {
			queue: false,
			duration: 240,
			complete: function() {

				/* Adjust Scrollbars for expanded content. */
				$(el).parents('.customScroll').jScrollPane(Scroll.options);

				$(el).children().css({
					'position': 'relative',
					'left': '-600px'
				}).show().animate({
					left: 0
				}, {
					queue: false,
					duration: 200,
					complete: function() {
						el.expanded = true;
						el.expanding = false;
					}
				}).filter('h2').css({
					'font-size': '1.8em',
					'line-height': '.7em',
					'letter-spacing': '-1px',
					'margin': '5px 0 0'
				});
			}
		});
		this.hide(el);
	},
	hide : function(except) {
		/* collapse all the expanded elements except the one being hovered */
		$(this.shows).each(function() {
			var el = this;
			if(el !== except && (el.expanded || el.expanding)) {
				if(el.expanding) {
					$(el).stop();
				}
				el.expanded = false;
				el.expanding = false;
				el.contracting = true;
				$(el).animate({
					height: 40,
					paddingTop: 0,
					paddingBottom: 0,
					paddingLeft: 0,
					paddingRight: 0,
					marginLeft: 15
				}, {
					queue: false,
					duration: 240,
					complete: function() {
						el.contracting = false;
					}
				}).children(':not(h2)').hide();
				$(el).children('h2').css({
					'font-size': '1.4em',
					'line-height': '1.4em',
					'letter-spacing': '0',
					'margin': '0 0 0 10px'
				});
				el = this;
				el.timer = setTimeout(function() {
					if(el.bgStep === 3) {
						$(el).css({
							'background-image': 'none',
							'background-color': '#F37B21'
						});
						el.bgStep = 2;
					}
					if(el.bgStep === 2) {
						$(el).animate({
							backgroundColor: '#6BC6E9'
						}, {
							queue: false,
							duration: 100,
							complete: function() {
								$(el).css({
									'background': 'transparent url(http://i.cdn.turner.com/v5cache/TBS/video/img/cmn/browse/bg_show.png) repeat-x 0'
								}).children('h2').css({
									'background': 'url(http://i.cdn.turner.com/v5cache/TBS/video/img/cmn/browse/icn_show.png) no-repeat 320px 20px'
								});
								el.bgStep = 0;
							}
						});
					}
					if(el.bgStep === 1) {
						$(el).css({
							'background': 'transparent url(http://i.cdn.turner.com/v5cache/TBS/video/img/cmn/browse/bg_show.png) repeat-x 0'
						}).children('h2').css({
							'background': 'url(http://i.cdn.turner.com/v5cache/TBS/video/img/cmn/browse/icn_show.png) no-repeat 300px 20px'
						});
						el.bgStep = 0;
					}
				}, 100);
			}
		});
	}
};

/**
 * @author Michael Bester
 * @constructor Share
 */
$(document).ready(function() {
	var share = new Share();
});
var Share = function() {
	this.init();
};
Share.prototype = {
	init : function() {
		$('ul#websites form').each(function(){
			$(this).attr("target","_blank");
		});
	}
};

/**
 * @author Michael Bester
 * @constructor Validate
 */
$(document).ready(function() {
	var validation = new Validate();
});
var Validate = function() {
	this.init();
};
Validate.prototype = {
	init : function() {
		var _this = this;
		$('form.validate').each(function(){
			var form = this;
			if (!this.validationSet) {
				$.each(_this.Methods, function(key, check){
					$('input.' + key + ",textarea." + key, form).each(function(){
						if (!this.checks) {
							this.checks = [];
						}
						this.checks.push(check);
					});
				});
				$(this).submit(function(){
					var form = this;
					form.allowSubmit = true;
					form.problems = [];
					$('*:enabled', this).each(function(){
						var input = this;
						if (input.checks) {
							$.each(input.checks, function(key, check){
								if(!check.method.call(input)) {
									form.problems.push({
										el : input,
										message : check.message
									});
									form.allowSubmit = false;
								}
							});
						}
					});
					/* Clean out any errors from previous submit attempts */
					this.cleanErrorMessages = function() {
						$('*.error', this).each(function(i, el){
							$(el).remove();
						});
					}();
					if (!this.allowSubmit) {
						/* We've got an error */

						this.errorHeader = '<h2 class="error">Please complete the required fields below:</h2>';
						$('legend', this).after(this.errorHeader);

						$.each(this.problems, function(key, problem){
							$('label', form).filter('[for=' + problem.el.id + ']').each(function(i, label) {
								label.err = ' <span class="error">[' + problem.message + ']</span>';
								$(label).append(label.err);
							});
						});

						/* For the sidebar */
						$(this).parents('.tabWrapper').each(function(i,wrapper){
							$(wrapper).find('li#nav_share').each(function(i, tab){
								wrapper.tabs.doSlideDown(tab);
							});
						});
					}
					//return form.allowSubmit;
					return false;
				});
				form.validationSet = true;
			}
		});
	},
	Methods : {
		required : {
			message : "required field",
			method : function() {
				return (this.value !== "") ? true : false;
			}
		}
	}
};

/**
 * @author Michael Bester
 * @constructor Window
 *
 * includes popup functionality
 */
$(document).ready(function() {
	var w = new Window();
});
var Window = function() {
	this.init();
};
Window.prototype = {
	init : function() {

		/* Every link with class ".popup" gets to open in a new window */
		$("a.popup").click(function() {
			window.open(this.href);
			return false;
		});
	}
};

/**
 * @author Michael Bester
 * @constructor Util
 *
 * includes copy to clipboard functionality
 * Credit where it's due : http://www.jeffothy.com/weblog/clipboard-copy/
 */
$(document).ready(function() {
	TBS.Util = new Util();
});
var Util = function() {
	this.init();
};
Util.prototype = {
	init : function() {
		var _this = this;
		if (!document.createTextRange) {
			_this.cpid = "clipboardProxy";
			_this.clipboardProxy = $('<div id="' + _this.cpid + '"></div>').css({
				position : "absolute",
				top : "-9999px",
				left : "-9999px"
			});
			$("body").append(_this.clipboardProxy);
		}
	},
	copyToClipboard : function(el) {

		/* Set some local variables */
		var text, range, cpSwf,
			_this = this;

		if (typeof el === "undefined") {
			return;
		}

		/* Handle Strings passed in. */
		text = (typeof el === "object") ? el.value : el;

		if (_this.clipboardProxy) { /* Non-IE */

			/* Switches embed writing method from SWFObject to innerHTML
			SWFObject for one bit of functionality is overkill. Also,
			This method does not require cross-browser compatibility,
			So it makes sense to use as little dependancies possible. */
			_this.clipboardProxy.empty();
			$("#" + _this.cpid).remove();
			$('<embed id="' + _this.cpid + '" src="http://i.cdn.turner.com/v5cache/TBS/TBS04/flash/static/clipboardProxy.swf" FlashVars="clipboard=' + encodeURIComponent(text) + '" width="0" height="0" type="application/x-shockwave-flash"></embed>').appendTo("body");

		} else {	/* IE */
			if (el.createTextRange) {
				range = el.createTextRange();
				if (range && (BodyLoaded == 1)) {
					range.execCommand("Copy");
				}
			}
		}

	}
};

/**
 * @author Richard Herrera
 *
 * Internet Explorer has a bug that, in effect, renders it's body height
 * as the height of _all_ elements, including hidden ones. Here we trigger
 * IE to redraw itself and correct its height.
 */
if($.browser.msie) {
	$(document).ready(function() {
		$("html").css("display", "none").css("display", "block");
	});
	/* And also to fix IE 6's caching of Background images */
	if ($.browser.version == "6.0") {
		try {
			document.execCommand("BackgroundImageCache", false, true);
		} catch(e) {}
	}
}

$(document).ready(function() {
	// Preload'n
	var I = new Image();
	I.src = "http://i.cdn.turner.com/v5cache/TBS/video/img/cmn/tab_scene.png";
});

/**
 * @author Richard Herrera
 *
 * Useless calls to prevent errors. They go to TBS' side of things
 */
var driver = driver || "",
    handleAddPlaylistItem = handleAddPlaylistItem || function() {},
    handleScrubbarEvent = handleScrubbarEvent || function() {},
    waitingVideo = "",
    lastTrackedVideo = new Object;