/**
 * CastFire Javascript player.
 * (c) CastFire.com 2009
 * @author Ivan Kirnev <ivan.kirnev@gmail.com>
 */

var CastfirePlayer = { version: "1.0" };
// Extending CastfirePlayer
$J.extend(true, CastfirePlayer, {
	players: [],        // list of registered players

	// Creates new player instance
	createPlayer: function(conf) {
		var player = this.getPlayer(conf.playerID);
		if (!player) {
			player = new castfire_player(conf);
			// registering new player
			this.players.push(player);
			player.init();
		}
		return player;
	},

	releasePlayer: function(playerId) {
		var p = this.getPlayer(playerId);
		if (p) { this.players.remove(p); }
	},

	getPlayer: function(playerId) {
		for (var i = 0, len = this.players.length; i < len; i++) {
			if (this.players[i].id === playerId) { return this.players[i]; }
		}
		return null;
	}
});

// =============================================
// Player
// =============================================
/**
 * Constructor of player instance
 * @param conf configuration parameters
 */
function castfire_player(conf) {
	// private member: storing initial configuration values
	var leftTabsHeight = 53;
	var rightTabsHeight = 26;
	this.initConf = conf;
	// player id
	this.id = conf.playerID;
	this.guid = conf.playerGuid;
	this.playerInstance = null;
	this.mainContainerId = this.id + '-cfp-mainContainer';     // div Id of main container
	this.leftPanelId = this.id + '-cfp-leftPanel';     // div Id of left panel
	this.rightPanelId = this.id + '-cfp-rightPanel';     // div Id of left panel
	this.tabsId = this.id + '-cfp-tabs';     // div Id of player tabs
	this.embedId = this.id + '-cfp-embedId'; // div Id of player embeded object
	this.playlistId = this.id + '-cfp-playlistId'; // div Id of player playlist object
	this.browseId = this.id + '-cfp-tabs-browse'; // div Id of player's browse button object
	this.queueId = this.id + '-cfp-tabs-queue'; // div Id of player's queue button object
	this.playlistUpId = this.id + '-cfp-playlistUpId'; // div Id of up button in playlist
	this.playlistDownId = this.id + '-cfp-playlistDownId'; // div Id of down button in playlist
	this.totalWidth = conf.totalWidth;
	this.totalHeight = conf.totalHeight;
	this.playerWidth = conf.playerWidth;
	this.playerHeight = conf.totalHeight - leftTabsHeight;//conf.playerHeight;
	this.playListHeight = this.playerHeight - rightTabsHeight;
	this.description = conf.description;
	this.tabInfos = {};     // helper object for internal usage
	this.selectedTabIdx = 0;
	this.selectedRightTabIdx = 0;
	this.selectedRightTabName = null;
	this.mouseOver = false;
	this.scrollClicked = false;
	this.el = null;
	this.playlists = {};
	this.queueData = { shows: [], sources: [] };		// creating an empty queue
	this.currentPlayList = null;
	this.currentShow = null;
	this.isInited = false;
};

// Extending castfire_player class with members and methods
$J.extend(true, castfire_player.prototype, {
	/**
	 * Shows player object
	 */
	show: function() {
	},

	/**
	 * Hides player object
	 */
	hide: function() {
	},

	init: function() {

		var player = this;	
		// init callback
		castfire_videoComplete = function(url){player.onCompleteMedia(url)};
		
		this.el = $J('#' + this.id);
		if( this.el && this.el.length > 0 ){
			this.el[0].innerHTML = this.generateHtml();
		}

		var selectBox = $J("#" + this.mainContainerId + " #myselectbox").selectbox();
		// setting up sizes of elements
		$J("#" + this.mainContainerId).width(this.totalWidth).height(this.totalHeight);
		$J('#' + this.leftPanelId).
			width(this.playerWidth).height(this.totalHeight);
		$J('#' + this.leftPanelId).width(this.playerWidth);
		var rightPanelWidth = this.totalWidth - this.playerWidth;
		$J('#' + this.rightPanelId).
			width(rightPanelWidth).height(this.totalHeight);
		$J('#' + this.rightPanelId + " .wrap2").width(rightPanelWidth);
		$J('#' + this.rightPanelId + " .playlist-container").height(this.playListHeight);
		$J('#' + this.embedId).height(this.playerHeight);
		

		this.playerInstance = this.getPlayerInstance("castfire_player-" + this.id);
		
		// setting up style changes on events
		$J("#" + this.mainContainerId + " li a").hover(
			function () { if (!$J(this).hasClass("active")) { $J(this).addClass("hover"); } },
			function () { $J(this).removeClass("hover"); }
		);

		// counting tabs total width to show/hide scrollers
		var tabEls = $J("#" + this.leftPanelId + " li");

		for (var i = 0, len = tabEls.length; i < len; i++) {
			var tabId = this.id + '-cfp-tabs-' + i;
			var tabEl = $J(tabEls.get(i));
			// set an id
			tabEl.attr("id", tabId).click(
				(function(player, tabId) {
					return function() {
						$J($J("#" + player.mainContainerId + " #myselectbox"+"_container ul li")[0]).click();
						player.onTabClicked(tabId); 
					}}) (this, tabId)
			);
			
			this.tabInfos[tabId] = {
				index: i, 
				width: tabEl.outerWidth(), 
				cfg: this.initConf.tabs[i],
				_default: this.initConf.tabs[i]['default']
			};
		}

		
		var selOts = $J("#" + this.mainContainerId + " #myselectbox").change(
				(function(player) {
					return function() {
					if(this.value == "0") return;
					var tabId = player.id + '-cfp-tabs-' + this.value;
					player.onTabClicked(tabId); }}) (this)
			)[0].options;

		for (var i = 0, len = selOts.length; i < len; i++) {
			var tabId = this.id + '-cfp-tabs-' + (tabEls.length + i);
			var tabEl = $J(selOts[i]);
			// set an id
			tabEl.attr("id", tabId);
			
			this.tabInfos[tabId] = {
				index: tabEls.length + i, 
				width: 0, 
				cfg: this.initConf.dropdown[i]
			};
		}

		// counting tabs total width to show/hide scrollers
		tabEls = $J("#" + this.rightPanelId + " .videonavigation li");
		for (var i = 0, len = tabEls.length; i < len; i++) {
			var tabEl = $J(tabEls.get(i));
			var tabId = tabEl.attr("id");
			tabEl.click(
				(function(player, tabId) {
					return function() { player.onRightTabClicked(tabId); }}) (this, tabId)
			);
			this.tabInfos[tabId] = { index: i, width: tabEl.width()};
		}
		
		// seting active tab
		this.onTabClicked(this.id + '-cfp-tabs-' + this.selectedTabIdx);
		this.selectedRightTabName = this.browseId;
		this.isInited = true;
		
		this.loadTagAlphabet(); //todo:
	},

	/**
	 * Returns player's html code
	 */
	generateHtml: function() {
		var arr = [
			"<div id=\"" + this.mainContainerId + "\" class=\"main-container\">",   // main container
			"<div id=\"" + this.leftPanelId + "\" class=\"left-column\">",      // left column
			"<ul class=\"topnavigation\" >"
		];
		var tabs = this.initConf.tabs;
		for (var i = 0, len = tabs.length; i < len; i++) {
			if(!tabs[i] || !tabs[i].name || !tabs[i].feed) continue;

			var name = tabs[i].name.replace(/^([^ ]*) ?(.*)?$/i, "$1 <span>$2</span>");
			var el = "<li><a "+ (tabs[i]['class']?"class=\""+ tabs[i]['class'] +"\"":"") +">" + name + "</a></li>"
			arr.push(el);
			if (tabs[i]['default'] && i !== 0) { this.selectedTabIdx = i; }
		}
		arr.push(
			"</ul>",
			"<div id=\"" + this.embedId + "\"class=\"castfire-player-container\">",
			this.generateEmbed(),
			"</div></div>",
			"<div id=\"" + this.rightPanelId + "\" class=\"right-column\">",
			"<div class=\"select\">",
				"<select id=\"myselectbox\" name=\"myselectbox\">",
				"<option value=\"0\">More Channels</option>"
		);
		
		var dropdown = this.initConf.dropdown;
		if(dropdown){
			for (var i = 0, len = dropdown.length; i < len; i++) {
				if(!dropdown[i] || !dropdown[i].name || !dropdown[i].feed) continue;

				var el = "<option value=\""+ (tabs.length + i) +"\" "+ (dropdown[i]['default']?"selected":"") +">"+ dropdown[i].name +"</option>";
				arr.push(el);
				if (dropdown[i]['default']) { this.selectedTabIdx = tabs.length + i; }
			}
		}
		arr.push(
				"</select>",
			"</div>",
			"<ul class=\"videonavigation\">",
				"<li id=\"" + this.id + "-cfp-tabs-browse\" ><a class=\"active\">Video</a></li>",
				"<li id=\"" + this.id + "-cfp-tabs-queue\" class=\"channels\"><a>My Channel</a></li>",
			"</ul>",
			"<div class=\"playlist-container\">",
			"</div>",
			"</div>",
			"</div>",
			"<div class=\"fortags\">",
				"<div class=\"links_alfabet\">",
					"<h2>Browse by Tags</h2>",
					"<ul class=\"menu\">",
					"</ul>",
				"</div>",
				"<div class=\"tags\">",
				"</div>",
			"</div>"
		);
		return arr.join('');
	},
	getPlayerInstance: function (id){	
		if(document.embeds[(id)])return document.embeds[id];
		if(window.document[(id)])return window.document[id];
		if(window[(id)])return window[id];
		if(document[(id)])return document[id];
		return null;
	},
	loadTagAlphabet: function(tabId){
		var url = this.initConf.apiUrl + "?api_key=" + this.initConf.key + "&method=public.getTagAlphabet&network_slug=" + this.initConf.network;
		var resp = $J.ajax({
			type: "GET", cache: false, async: false,
			url: url,
			dataType: this.initConf.apiUrl.indexOf(".json") != -1 ?  "json" : "jsonp",
			success: (function(player) { return function(data, status) {
						player.setTagAlphabet(data);}; }) (this)
		});
	},
	setTagAlphabet: function(data){
		if(!data || !data.letters || !data.letters.letter) return;
		var ulInner = "";
		for (var i = 0, len = data.letters.letter.length; i < len; i++) {
			var lr = data.letters.letter[i]
			
			if ( !(lr._content >= "0" && lr._content <= "9") ){
				ulInner += "<li><a count=\""+lr.count+"\">"+lr._content+"</a></li>";
			}
		}
		
		$J("#" + this.id + " .fortags .links_alfabet .menu").html(ulInner);
		var first = $J("#" + this.id + " .fortags .links_alfabet .menu li a").click(
					(function(player) { return function() {
						if($J(this).attr("count") == 0) return;
						player.loadTags($J(this).html());
					}; }) (this)
				)[0];
		$J(first).click();
	},
	loadTags: function(letter){
		var url = this.initConf.apiUrl + "?api_key=" + this.initConf.key + "&method=public.getTags&network_slug=" + this.initConf.network + "&tag_first_letter=" + letter;
		var resp = $J.ajax({
			type: "GET", cache: false, async: false,
			url: url,
			dataType: this.initConf.apiUrl.indexOf(".json") != -1 ?  "json" : "jsonp",
			success: (function(player, letter) { return function(data, status) {
						player.setTags(data, letter);}; }) (this, letter)
		});
	},
	setTags: function(data, letter){
		if(!data || !data.tags || !data.tags.tag) return;
		var htmlArr = [
			"<div class=\"scroller-up\"></div>",
			"<div class=\"scrollWrapper\"><table>",
				"<tr>"
		];
		for (var i = 0, len = data.tags.tag.length; i < len; i++) {
			htmlArr.push(
				"<td><a title=\"" + data.tags.tag[i].count + " show" + (data.tags.tag[i].count!=1?"s":"") + "\">" + data.tags.tag[i]._content + "</a></td>"
			);
			if( (i+1)%3 == 0 ){
				htmlArr.push("</tr><tr>");
			}
		}
		htmlArr.push(
				"</tr>",
			"</table></div>",
			"<div class=\"scroller-down\"></div>"
		);
		$J("#" + this.id + " .fortags .tags").html(htmlArr.join(''));

		$J("#" + this.id + " .fortags .tags").divScroll({scrollSpeed:this.initConf.scrollSpeed});
		var tabEls = $J("#" + this.id + " .fortags .tags table tr td a");

		for (var i = 0, len = tabEls.length; i < len; i++) {
			var tabId = this.id + '-cfp-tabs-' + letter + '-' + i;
			var tabEl = $J(tabEls.get(i));
			// set an id
			tabEl.attr("id", tabId).click(
				(function(player, tabId) {
					return function() {
						$J($J("#" + player.mainContainerId + " #myselectbox"+"_container ul li")[0]).click();
						player.onTabClicked(tabId); 
					}}) (this, tabId)
			);
			this.tabInfos[tabId] = {
				index: i, 
				width: 0, 
				cfg: { name: tabEl.html(), feed: "http://feeds.castfire.com/json/20/redskins/tag:" + tabEl.html() + "/"}
			};
		}
	},
	onTabClicked: function(tabId) {
		var tabObj = this.tabInfos[tabId];
		if (tabObj) {
			//if (tabObj.index === this.selectedTabIdx && this.isInited) { return; }
			var prevId = "#" + this.id + '-cfp-tabs-' + this.selectedTabIdx + " a";
			$J(prevId).removeClass("active");
			$J("#" + tabId + " a").addClass("active").removeClass("hover");
			this.selectedTabIdx = tabObj.index;
			this.onRightTabClicked(this.browseId);

			if (this.currentPlayList) {
				var pl = this.playlists[this.currentPlayList];
				if (pl) { $J("#" + pl.divId).hide(); }
				
				pl = this.playlists[tabId];
				if (pl) { 
					$J("#" + pl.divId).show(); 
					this.currentPlayList = tabId;
					return;
				}
			}

			var divId = tabId + "-playlist";
			//$J("#" + divId).remove();
			var htmlArr = [
				"<div id=\"" + divId + "\">",
				//"<div class=\"scroller-up\"></div>",
				"<div class=\"playlist-loading\"> </div>",
				//"<div class=\"scroller-down\"></div>", 
				"</div>"
			]
			$J('#' + this.rightPanelId + " .playlist-container").
				append(htmlArr.join(''));
			//return;//todo:
			var info = this.tabInfos[tabId];
			if (info) {
				var resp = $J.ajax({
					type: "GET", cache: false, async: false,
					url: info.cfg.feed + (info._default && this.initConf.sh ?"sh:"+ this.initConf.sh +"/":""),
					dataType: info.cfg.feed.indexOf(".json") != -1 ?  "json" : "jsonp",
					success: (function(player, tabId) { return function(data, status) {
								player.updatePlayList(tabId, data, "browse");}; }) (this, tabId)

				});
			}
		}
	},
	onRightTabClicked: function(tabId) {
		if (tabId === this.selectedRightTabName) { return; }
		var re = new RegExp("(.*)-cfp-tabs-(.*)", "gi");
		var res = re.exec(tabId);	// res[1] - playerId; res[2] - tabCommand
		if (res != null) {
			var cmd = res[2];
			if (cmd === "browse") {
				var browsePl = (!this.currentPlayList) ? null :
						this.playlists[this.currentPlayList];
				var pl = this.playlists[this.selectedRightTabName];
				if (browsePl) { $J("#" + browsePl.divId).show(); }
				if (pl) { $J("#" + pl.divId).hide(); }

			} else if (cmd === "queue") {
				if (!this.playlists[tabId]) {
					// create playlist for queue
					this.updatePlayList(tabId, this.queueData, "queue");
				}
				var browsePl = (!this.currentPlayList) ? null :
						this.playlists[this.currentPlayList];
				var pl = this.playlists[tabId];
				if (browsePl) { $J("#" + browsePl.divId).hide(); }
				if (pl) { $J("#" + pl.divId).show(); }
			} else {
				// unknown tab - quit
				return;
			}
			$J("#" + this.selectedRightTabName + " a").removeClass("active");
			$J("#" + tabId + " a").addClass("active");
			this.selectedRightTabName = tabId;
			this.selectItem(this.currentShow);
		}
	},
	updatePlayList: function(tabId, data, mode) {
		var divId = tabId + "-playlist";
		$J("#" + divId).remove();
		var htmlArr = [
			"<div id=\"" + divId + "\">",
			"<div class=\"scroller-up\"></div>",
			"<ul class=\"rightnavigation\">"
		];

		if (data.shows) {
			// iterating thru the show array
			for (var i = 0, len = data.shows.length; i < len; i++) {
				var show = data.shows[i];
				show.nextShow = data.shows[(i+1!=len)?i+1:0];
				show.nextShow.prevShow = show;
				htmlArr.push(this.getItemHtml(divId, show, mode, i));
			}
		}
		htmlArr.push(
			"</ul>",
			"<div class=\"scroller-down\"></div>", 
			"</div>"
		);
		$J('#' + this.rightPanelId + " .playlist-container").
			append(htmlArr.join(''));
		
		var divScroll = $J('#' + divId).divScroll({
			height:this.playListHeight, 
			scrollSpeed:this.initConf.scrollSpeed,
			scrollWrapper:"ul.rightnavigation",
			callbackEndForward: (function(player, tabId) { return function() {
								player.loadNextPage(tabId);}; }) (this, tabId)
		});
		
		var pl = { divId: divId, data: data, divScroll: divScroll, topItem: 0,
			maxItem: (data.shows && data.shows.length > 0) ? data.shows.length - 1 : 0};
		this.playlists[tabId] = pl;
		
		if (data.shows) {
			// binding events to buttons
			for (var i = 0, len = data.shows.length; i < len; i++) {
				var show = data.shows[i];
				var itemId = divId + "-" + show.show_id;
				if (mode === "browse") {
					$J("#" + itemId + " .add").click(
						(function(player, itemId, show) { return function(ev) {
							ev.stopPropagation();
							player.addToQueueClicked(itemId, show); }; }) (this, itemId, show)
					);
					
					if( this.queueData && this.queueData.sources && this.queueData.sources[itemId] ) {
						$J("#" + itemId + " .add").hide();
					} 
				}
				if (mode === "queue") {
					$J("#" + itemId + " .remove").click(
						(function(player, itemId, show) { return function(ev) {
							ev.stopPropagation();
							player.removeFromQueueClicked(itemId, show); 
							}; }) (this, itemId, show)
					);
				}
				$J("#" + itemId + " .image").click(
					(function(player, show) { return function() {
						player.playMedia(show); }; }) (this, show)
				);
				$J("#" + itemId + " h3").click(
					(function(player, show) { return function() {
						player.playMedia(show); }; }) (this, show)
				);
			}
		}
		if (mode === "browse") {
			this.currentPlayList = tabId;
		}
		
		if (!this.currentShow && data && data.shows && data.shows.length > 0 ){
			this.loadMedia(data.shows[0]);
		}
	},

	getItemHtml: function(divId, show, mode, i, hidden) {
		var itemId = divId + "-" + show.show_id;
		var date = new Date(show.pubdate);
		var htmlArr = [
			"<li id=\"" + itemId + "\" " + (hidden == "hidden"? " style=\"display: none;\" ":"") + " " + (i%2 == 1 ? " class=\"bg\" " : "") + " >",
				"<span>",
					(mode !== "browse") ? "<a class=\"remove\"></a>":"<a class=\"add\"></a>",			
					"<a class=\"image\">",
					(!show.images || !show.images.tmb) ? "" :
						"<img src=\"" + show.images.tmb + "\" alt=\"\">",
					"</a>",
					"<p>"+ (date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear() +"</p>",
					"<h3>" + show.title + "</h3>",
					(this.description == "true") ? "<p>" + show.description + "</p>":"",
				"</span>",
			"</li>"
		];
		return htmlArr.join('');
	},

	loadNextPage: function(tabId){
		if( this.loading||
			tabId == this.queueId || 
			tabId != this.currentPlayList ){ return; }

		var info = this.tabInfos[tabId];
		var pl = this.playlists[tabId];
		if ( !info || !pl || !pl.data || !pl.data.pagination || "" == pl.data.pagination.next /*|| !pl.data.shows*/ ) { return; }

		pl.divScroll.append("<li class=\"playlist-loading\"> </li>");
		pl.divScroll.onScrollerForward(500, true, function(){});
		this.loading = true;

		var itemsPerPage = "10";
		var feed = pl.data.pagination.next.replace(/(^.*\/json\/\d+:)\d+(\/.*$)/i, "$1" + itemsPerPage + "$2");
		var resp = $J.ajax({
			type: "GET", cache: false, async: true,
			url: feed, //pl.data.pagination.next,
			dataType: info.cfg.feed.indexOf(".json") != -1 ?  "json" : "jsonp",
			success: (function(player, tabId) { return function(data, status) {
				player.loading = false;
				player.addNextPageToList(tabId,  data)}; }) (this, tabId)

		});
		
	},
	addNextPageToList: function(tabId,  data){//debugger;
		var pl = this.playlists[tabId];
		if (!pl || !pl.data || !pl.data.shows || !data || !data.shows) { return; }
		var divId = pl.divId;
		var htmlArr = [];

		// iterating thru the show array
		for (var i = 0, len = data.shows.length; i < len; i++) {
			var show = data.shows[i];
			var j = pl.data.shows.length;
			pl.data.shows[j] = show;
			show.nextShow = pl.data.shows[0];
			show.nextShow.prevShow = show;
			show.prevShow = pl.data.shows[j-1];
			show.prevShow.nextShow = show;
			
			htmlArr.push(this.getItemHtml(divId, show, "browse", j, "hidden"));
		}

		pl.divScroll.append(htmlArr.join(''));
		pl.maxItem = pl.data.shows.length - 1;
		pl.data.pagination = data.pagination;
		
		for (var i = 0, len = data.shows.length; i < len; i++) {
			var show = data.shows[i];
			var itemId = divId + "-" + show.show_id;
			$J("#" + itemId + " .add").click(
				(function(player, itemId, show) { return function(ev) {
					ev.stopPropagation();
					player.addToQueueClicked(itemId, show); }; }) (this, itemId, show)
			);
			
			if( this.queueData && this.queueData.sources && this.queueData.sources[itemId] ) {
				$J("#" + itemId + " .add").hide();
			}
			
			$J("#" + itemId + " .image").click(
				(function(player, show) { return function() {
					player.playMedia(show); }; }) (this, show)
			);
			$J("#" + itemId + " h3").click(
				(function(player, show) { return function() {
					player.playMedia(show); }; }) (this, show)
			);
		}	
		var itemId = divId + "-" + data.shows[data.shows.length-1].show_id;
		$J("#" + itemId + " .tumb").ready(
			(function(player, pl, divId) { return function() {
				setTimeout(
					(function(player, pl, divId) { return function() {
						pl.divScroll.remove(".playlist-loading");
						pl.divScroll.show("li");
					}; }) (player, pl, divId)
				, 500)
			}; }) (this, pl, divId)
		);
	},
	addToQueueClicked: function(itemId, show) {
		this.queueData.shows.push(show);
		show.itemId = itemId;
		this.queueData.sources[itemId] = itemId;
		var tabId = this.id + "-cfp-tabs-queue";
		var divId = tabId + "-playlist";
		$J("#" + itemId + " .add").hide();
		$J("#" + tabId + " a").text(
				"My Channel (" + this.queueData.shows.length + ")");
		var pl = this.playlists[tabId];
		if (pl) {
			var html = this.getItemHtml(divId, show, "queue", this.queueData.shows.length-1);
			pl.divScroll.append(html);
			pl.maxItem++;
			if (this.queueData.shows) {
				// iterating thru the show array
				for (var i = 0, len = this.queueData.shows.length; i < len; i++) {
					var show = this.queueData.shows[i];
					show.nextShow = this.queueData.shows[(i+1!=len)?i+1:0];
					show.nextShow.prevShow = show;
				}
			}
			
			var queueItemId = divId + "-" + show.show_id;
			$J("#" + queueItemId + " .remove").click(
					(function(player, queueItemId, show) { return function(ev) {
						ev.stopPropagation();
						player.removeFromQueueClicked(queueItemId, show); 
						}; }) (this, queueItemId, show)
			);
			
			$J("#" + queueItemId + " .image").click(
				(function(player, show) { return function() {
					player.playMedia(show); }; }) (this, show)
			);
			$J("#" + queueItemId + " h3").click(
				(function(player, show) { return function() {
					player.playMedia(show); }; }) (this, show)
			);
			this.selectItem(this.currentShow);
		}
	},
	removeFromQueueClicked: function(itemId, show){
		this.queueData.shows.remove(show);
		this.queueData.sources[show.itemId] = null;
		var tabId = this.id + "-cfp-tabs-queue";
		var divId = tabId + "-playlist";
		$J("#" + show.itemId + " .add").show();
		
		if (this.queueData.shows.length == 0){
			$J("#" + tabId + " a").text("My Channel");
		}else{
			$J("#" + tabId + " a").text(
				"My Channel (" + this.queueData.shows.length + ")");
		}
		var pl = this.playlists[tabId];
		if (pl) {
			pl.maxItem--;
			pl.divScroll.remove("#" + itemId);
		}
		show.prevShow.nextShow = show.nextShow;
		show.nextShow.prevShow = show.prevShow;
		show = null;
	},
	playMedia: function(show) {
		if (this.playerInstance) {
			this.selectItem(show);
			try{
				this.playerInstance.externalCastfirePlayVideo(show.url);
			}catch(e){}
		}
	},
	loadMedia: function(show, deep) {
		deep = deep?deep:0;
		if(deep>10) return;
		
		if (this.playerInstance) {
			this.selectItem(show);
			try{
				this.playerInstance.externalCastfireLoadVideo(show.url);
			}catch(e){
				setTimeout(
				(function(player, show, deep) { return function() {
					player.loadMedia(show,++deep); }; }) (this, show, deep)
				, 500);
			}
		}
	},
	onCompleteMedia: function(url){
		if(!this.currentShow) return;
		var tmpShow = this.currentShow;
		if(this.selectedRightTabName == this.queueId){
			this.removeFromQueueClicked(tmpShow.oDiv.attr("id"), tmpShow); 
			if( this.queueData.shows.length == 0 ){
				this.currentShow = null;
				return;
			}
		}
		this.playMedia(tmpShow.nextShow);

	},
	selectItem: function(show) {
		if(this.currentShow && this.currentShow.oDiv){
			this.currentShow.oDiv.removeClass("playlist-item-selected");
		}
		if(show){
			var curPL = this.selectedRightTabName == this.queueId?this.queueId:this.currentPlayList;
			var	itemId = curPL + "-playlist-" + show.show_id;
			show.oDiv = $J("#" + itemId);
			show.oDiv.addClass("playlist-item-selected");
			this.currentShow = show;
		}
	},
	generateEmbed: function() {
		var plId = "castfire_player-" + this.id;
		var url = "http://p.castfire.com/" + this.guid + "/video/unloaded";
		var tmpl = [
				'<object width="', this.playerWidth, '" height="100%" id="', plId ,'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000">',
					'<param name="movie" value="http://p.castfire.com/' + this.guid + '/video/unloaded"></param>',
					'<param name="allowFullScreen" value="true"></param>',
					'<param name="allowScriptAccess" value="always"></param>',
                    '<param name="wmode" value="opaque"></param>',
					'<embed ',
						'width="', this.playerWidth, '" height="100%" ',
						'src="http://p.castfire.com/' + this.guid + '/video/unloaded" ',
						'id="', plId ,'" ',
						'type="application/x-shockwave-flash" ',
						'allowFullScreen="true" wmode="opaque"',
						'allowScriptAccess="always">',
					'</embed>',
				'</object>'
		];
		return tmpl.join(''); //todo:
	},
	generateInitialEmbed: function(guid, width, height, playerId, show) {
		/*
		<embed id="castfire_player_1812_flv" class="castfire_player"
			height="354" width="425" pluginspage="http://www.macromedia.com/go/getflashplayer"
			type="application/x-shockwave-flash" allowscriptaccess="always"
			name="castfire_player_1812_flv" wmode="transparent" quality="low"
			src="http://p.castfire.com/cHNHf/video/1812/webbalert_2007-08-02-024247.flv"/>
		 */
		var plId = this.id + "-" + show.show_id;
		var url = "http://p.castfire.com/" + show.show_id + "/unloaded/";
		/*
		var tmpl = [
			"<embed id=\"" + plId + "\" class=\"castfire_player\"",
			" height=\"" + height +  "\" width=\"" + width + "\" ",
			" pluginspage=\"http://www.macromedia.com/go/getflashplayer\"",
			" name=\"" + plId + "\" wmode=\"transparent\" quality=\"low\"",
			" src=\"" + url + "\"/>"
		];
		*/
		var tmpl = [
			'<object width="', width, '" height="', height,
			'" id="player', playerId, '" name="player', playerId,
			'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000">',
			'<param name="movie" value="' + url + '"></param>',
			'<param name="allowFullScreen" value="true"></param>',
			'<param name="allowScriptAccess" value="always"></param>',
            '<param name="wmode" value="opaque"></param>',
            '<embed width="', width , '" height="', height,
			'" src="' + url + '" id="player', playerId,
			'" name="player', playerId, '" type="application/x-shockwave-flash"',
			' allowFullScreen="true" wmode="opaque" allowScriptAccess="always"></embed>',
			'</object>'
		];
		return tmpl.join('');
	}
});

$J.extend(true, Array.prototype, {
	/**
	 * Checks whether or not the specified object exists in the array.
	 * @param {Object} o The object to check for
	 * @return {Number} The index of o in the array (or -1 if it is not found)
	 */
	indexOf : function(o){
		for (var i = 0, len = this.length; i < len; i++){
			if(this[i] == o) return i;
		}
		return -1;
	},

	/**
	 * Removes the specified object from the array.  If the object is not found nothing happens.
	 * @param {Object} o The object to remove
	 * @return {Array} this array
	 */
	remove : function(o) {
		var index = this.indexOf(o);
		if(index != -1) { this.splice(index, 1); }
		return this;
	}
});