/* mftv 2.3.1
 * @author: Jon Lebensold - jon@lebensold.net
 */
function resetPager() 
{
	currentPage = 1;
}
function getprevpage() 
{
	if (currentPage === 1) 
		return false;
	
	var page = parseInt(currentPage) - 1;
	if (currentPlaylist == -1)
		$.historyLoad(url("channel/"+currentChannel+"/p/"+page)); 
	else
		$.historyLoad(url("channel/"+currentChannel+"/p/"+page+"/pl/"+currentPlaylist)); 

}
function getnextpage() 
{
	if (numberOfPages === currentPage) 
		return;
	
	var page = parseInt(currentPage) + 1;
	if (currentPlaylist == -1)
		$.historyLoad(url("channel/"+currentChannel+"/p/"+page)); 
	else
		$.historyLoad(url("channel/"+currentChannel+"/p/"+page+"/pl/"+currentPlaylist)); 

}

function toPage(number) 
{
	if (currentPlaylist == -1)
		$.historyLoad(url("channel/"+currentChannel+"/p/"+parseInt(number))); 
	else
		$.historyLoad(url("channel/"+currentChannel+"/p/"+parseInt(number)+"/pl/"+currentPlaylist)); 
}
 
function loadPage(callback) 
{
	$("#loading").show();

	$.post(url("async/getvideosbypage"), {
		"page" :currentPage,
		"channel" :currentChannel.toLowerCase(),
		"plid" :currentPlaylist,
		"search" :searchQuery
	}, function(data) {
		$("#loading").hide();
		if (data.pager)
			loadPaginator(data.pager);

		if (!data.videos) {

			$("#categorylist ul").empty();
			$("#ddlplaylist").empty();
			$('#categorylist ul').html("<li><h2 style='color:#FFF'>no videos found</h2></li>");
			return;
		}

		loadGrid(data.videos);
		if (searchQuery.length == 0)
		{
			if (data.playlists) 
				populatePlaylist(data.playlists);
			
			prePlayVideo($('#videogrid').children(":first"));
		}
		
		if (callback)
			callback();
			
		
	}, 'json');
}
function togglePlaylist()
{
	
	$("body").bind('click.ddl' , function() 
			{
				$("#playlistDDL .open").removeClass('open').addClass('closed');
				$("body").unbind('click.ddl');
			});
	$("#playlistDDL").find("li a").click(filterByPlaylist);

	if( $("#playlistDDL").find(":nth-child(1)").hasClass('closed'))
	{
		$("#playlistDDL .closed").removeClass('closed').addClass('open');	
	}
	else
	{
		$("#playlistDDL .open").removeClass('open').addClass('closed');
		$("body").unbind('click.ddl');
	}	
	
}
function populatePlaylist(playlists) 
{
	$("#playlistDDL").show();
	$("#playlistDDL ul").empty();
	var allPlaylistText = currentChannel.toUpperCase() + ": All Playlists";
	$("#playlistDDL div.current a").attr("rel", "").text(allPlaylistText);
	$("#playlistDDL ul").append("<li><a href='#' rel=''>"+allPlaylistText+"</a></li>");
	for ( var i = 0; i < playlists.length; i++) {
		var selected = '';
		if (currentPlaylist == playlists[i].id) {
			$("#playlistDDL div.current a").attr('rel',playlists[i].id).text(playlists[i].title);
			selected = "class='current'";
		}

		$("#playlistDDL ul").append(
				"<li " + selected + "><a href='#' rel='" + playlists[i].id + "'>"
						+ playlists[i].title + "</a></li>");
	}
	if (playlists.length > 10)
		$("#playlistDDL ul").css({"height":"300px","overflow":"scroll"});	
	else
		$("#playlistDDL ul").css({"height":"auto","overflow":""});
}
function filterByPlaylist() 
{
	
	
	$("#playlistDDL .closed").removeClass('closed').addClass('open');
	if ($(this).attr("rel") == "") 
		$.historyLoad(url("channel/"+currentChannel+"/p/"+1)); 
	else 
		$.historyLoad(url("channel/"+currentChannel+"/p/"+1+"/pl/"+$(this).attr("rel"))); 
	
	
}

function loadPaginator(pager) 
{
	$('.pagerlink').remove();
	numberOfPages = pager.numpages;
	for ( var i = 0; i < pager.pagerrange.length; i++) {
		var pagerclass = '';
		if (pager.pagerrange[i] === parseInt(currentPage)) {
			pagerclass = 'current';
		}
		$(".paginationnext").before(
				"<li><a page='" + pager.pagerrange[i] + "' class='pagerlink "
						+ pagerclass + "' onclick='toPage(\""
						+ pager.pagerrange[i] + "\");return false;' href='#'>"
						+ pager.pagerrange[i] + "</a></li>");
	}
}
function loadGrid(videos) {
	$("#categorylist ul").empty();
	for ( var i = 0; i < videos.length; i++)
		$("#categorylist ul").append(getmfvitem(videos[i]));

	initGridListeners();
}
function getmfvitem(video) 
{
	
	if (dtoNameToCommaList(video.SecondaryAuthors).length == 0)
		var musicHTML = "";
	else
		var musicHTML = "<h4 class='audioauthor'>MUSIC: "
		+ dtoNameToCommaList(video.SecondaryAuthors) + "</h4>"; 

	return "<li beid='" + video.botrCode + "' botrcode='" + video.botrCode
			+ "' vid='" + video.id + "' >" + "<a botrcode='" + video.botrCode
			+ "' href='#'><img src='" + getLargeBotrThumbUrl(video.botrCode)
			+ "' height='90' width='120' /></a>"
			+ "<div class='hovervideooverlay'>"
			+ "<div class='hovervideooverlaybuttons'>"
			+ "<a href='#' class='icon playvideo'>PLAY VIDEO</a>"
			+ "<a href='#' class='icon addtoqueue'>ADD TO QUEUE</a>"
			+ "</div></div>" + "<div class='hovervideopopup'>"
			+ "<span class='hovervideopopuparrow'></span>"
			+ "<h3 class='title'>" + video.title + "</h3>"
			+ "<h4 class='videoauthor '>VIDEO: "
			+ dtoNameToCommaList(video.PrimaryAuthors) + "</h4>"
			+ musicHTML
			+ "<div class='description'>"
			+ video.description + "</div></div></li>";
}

function toggleMyQueue() 
{
	queueIsOpen = !queueIsOpen;
	if (queueIsOpen)
	{
		$(".overlay").css("height","1500px");	
		$(this).addClass("active");
	}
	else
	{
		$(".overlay").css("height","1360px");	
		$(this).removeClass("active");
	}
		
	
	
	$("#tvqueuecontrols_options").toggle();
	$("#tvqueue").toggle();
	return false;
}
function addallToQueue() 
{
	if (!queueIsOpen)
		toggleMyQueue();
	$('#categorylist ul li').each( function(emt) {
		addToQueue($(this));
	});
	return false;
}
function toggleShuffleQueue() {
	isShuffle = !isShuffle;
	if (isShuffle) 
		$(this).addClass("active");
	else 
		$(this).removeClass("active");	

	return false;
}

function clearQueue() {
	$("#tvqueueitems").empty();
	return false;
}
function addToQueue(emt) {
	if (!queueIsOpen)
		toggleMyQueue();

	var botrCode = $(emt).attr("botrcode");
	var beid = $(emt).attr("botrcode");
	var desc = $(emt).find('.description').html();
	
	$("#tvqueueitems")
			.append(
					"<li beid='"
							+ beid
							+ "' botrcode='"
							+ botrCode
							+ "' ><a href='#'>"
							+ $(emt).find("a").html()
							+ "</a><div class='hovervideooverlay' style='display:none;'>"
							+ "<h3 class='title'>"
							+ $(emt).find('.title').html()
							+ "</h3>"
							+ "<span class='videoauthor' style='display:none;'>"
							+ $(emt).find('.videoauthor').text()
							+ "</span>"
							+ "<span class='audioauthor' style='display:none;'>"
							+ $(emt).find('.audioauthor').text()
							+ "</span>"
							+ "<span class='description' style='display:none;'>"
							+ $(emt).find('.description').html()
							+ "</span>"
							+ "<div class='hovervideooverlaybuttons'>"
							+ "<a href='#' class='icon playvideo'>PLAY VIDEO</a>"
							+ "<a href='#' class='icon removefromqueue'>REMOVE FROM QUEUE</a>"
							+ "</div>" + "</div></a></li>");
	queue.slider.addElement($("#tvqueueitems").children(":last"));

}
function playVideoFromQueue() 
{
	return false;
}

function changeChannel(emt, id) 
{
	currentPlaylist = -1;
	searchQuery = "";

	$("#ddlplaylist").show();
	
	$('#categorytabs li').removeClass('active');
	if (emt.length < 1)
	{
		var tag = document.getElementById(id);
		tag.parentNode.className = 'active';
		
		currentChannel = tag.text;
	}
	else
	{
		emt.parent().show();
		
		emt.parent().addClass('active');
		if (emt.attr('id') == "tab_99cdreams")
			currentChannel = "99c dreams";
		else
			currentChannel = emt.text();
	}
	
	resetPager();
}
function showtvdesc()
{
	if (descIsOpen) return; 
	$("#tvdesc").fadeIn('fast');
	$("#tvdescbtn").addClass('open');
	descIsOpen = !descIsOpen;
	
	//Active le scroll pour la dest
	makeScrollable($('#tvdesc .description-wrapper'));
}
function hidetvdesc()
{
	if (!descIsOpen) return;
	$("#tvdesc").fadeOut('fast');
	$("#tvdescbtn").removeClass('open');
	descIsOpen = !descIsOpen;
		
}

function toggledesc()
{
	if (descIsOpen)
		hidetvdesc();		
	else
		showtvdesc();
	return false;
}
function makePlaylist() {	player.addModelListener("STATE", "stateTracker"); }
function updatetvdesc()
{
	$('#tvdesc .title').text(nowPlaying.title);
	$('#tvdesc .creditvideo').text(nowPlaying.videoAuthors);

	if (nowPlaying.audioAuthors == null)
		$('#tvdesc .creditaudio').hide();
	else
		$('#tvdesc .creditaudio').show();
	$('#tvdesc .creditaudio').text(nowPlaying.audioAuthors);
	$('#tvdesc .description').html(nowPlaying.description);
}

function playVideo() {
	if (player == null || typeof(player.sendEvent) == "undefined" )
	{
		player = $("#mpl").get(0);
		setTimeout(playVideo, 500);
		return;
	}
	/*
     * For out of nomadsplayer.tv implementation
     */
    /*document.title = nowPlaying.title + " in " + currentChannel.toUpperCase()
			+ " | NOMAD Player";
	var botr = nowPlaying.botrCode;
	
	setTimeout(showtvdesc,500);
	setTimeout(hidetvdesc,4000);
	
	updatetvdesc();
	*/
	//for offline development
	//var obj = {
	//		"file" :  '/offline/offline.flv',
	//		type :'video'
	// };
	
	var obj = {
		"file" :  'http://content.bitsontherun.com/videos/' + player.botrCode + '-34283.m4v',
		type :'video'
	};
	
	
	//player.botrCode = botr;
	player.sendEvent("LOAD", obj);
	//if (!isPlayingVideo)
	player.sendEvent("PLAY", "true");
	/*
	updateModals();

	// slide to
	if (firstvideoPlayed)
		scrollTo("#sitehdr");
	else
		firstvideoPlayed = true;
	
	isPlayingVideo = true;
    */
}
function prePlayVideo(emt)
{
	$('#tvqueueitems li').removeClass('current');
	$('#videogrid li').removeClass('current');
	mapVideoElementToNowPlaying(emt);
	
	if (searchQuery.length == 0)
	{//BROWSING
			if (currentPlaylist == -1)
				$.historyLoad(url("channel/"+currentChannel+"/p/"+currentPage+"/v/"+nowPlaying.beid+"/"+encodeURIComponent(nowPlaying.title))); 
			else
				$.historyLoad(url("channel/"+currentChannel+"/p/"+currentPage+"/pl/"+currentPlaylist+"/v/"+nowPlaying.beid+"/"+encodeURIComponent(nowPlaying.title))); 
	}
	else
	{//SEARCHING
		$.historyLoad(url("search/"+currentChannel+"/p/"+currentPage+"/q/"+encodeURIComponent(searchQuery)+"/v/"+nowPlaying.beid+"/"+encodeURIComponent(nowPlaying.title))); 		
	}
}
function getVideoUrl() 
{
	if (isSearch == "true")
		return "http://" + host + "/search/"+currentChannel+"/p/"+currentPage+"/q/"+searchQuery+"/v/"+nowPlaying.beid+"/"+encodeURIComponent(nowPlaying.title); 
	else if (currentPlaylist == -1)
		return "http://" + host + "/channel/"+currentChannel+"/p/"+currentPage+"/v/"+nowPlaying.beid+"/"+encodeURIComponent(nowPlaying.title); 
	else
		return "http://" + host + "/channel/"+currentChannel+"/p/"+currentPage+"/pl/"+currentPlaylist+"/v/"+nowPlaying.beid+"/"+encodeURIComponent(nowPlaying.title); 

	
}
function updateModals() 
{
	var url = getVideoUrl();
	$(".videourl").val(url);
	$("#frmsendtext")
			.val(
					'Hi There, \nI saw this video and thought you might like it:\n--------\n'
							+ nowPlaying.title
							+ ':\n'
							+ url
							+ '\n\n-----\n'
							+ nowPlaying.description);
	$("#modalfrmembedcode").val(
			'<script type="text/javascript" src="http://' + host + '/embed/'
					+ nowPlaying.beid + '.js"></script>');
	$("#mailsent").hide();
	$("#modalfrmsend").show();

}
function mapVideoElementToNowPlaying(emt) 
{
	
	nowPlaying.botrCode = emt.attr('botrcode');
	nowPlaying.title = emt.find('.title').text();
	nowPlaying.videoAuthors = emt.find('.videoauthor').html();
	nowPlaying.audioAuthors = emt.find('.audioauthor').html();
	nowPlaying.description = emt.find('.description').html();
	nowPlaying.beid = emt.attr('botrcode');
	$("li[botrcode='"+nowPlaying.botrCode+"']").addClass('current');
		
}
function searchVideos(query) 
{
	lastQuery = query;
	searchQuery = query;
	searchChannel = currentChannel;
	if (query.length === 0) 
		return false;
	
	var searchTab = $("#categorytabs .search");
	$("#tabtbsearch").val(query);			
	searchTab.show();
	$("#playlistDDL").hide();
	$('#categorytabs li').removeClass('active');
	searchTab.addClass('active');
	return false;
}

function stateTracker(obj) 
{
	if (obj.newstate != 'PLAYING' && obj.newstate != 'COMPLETED' )
		isPlayingVideo = false;
	if (obj.newstate == 'COMPLETED') {
		player.bReloadPlaylist = true;
		if (player.getConfig().item == player.getPlaylist().length - 1) {
			
			player.sendEvent('PLAY', 'false');
			if (queueIsOpen) {
				$('#tvqueueitems li').removeClass('current');
				$('#videogrid li').removeClass('current');
				
				if (isShuffle) {
					var playme = rand(0, queue.slider.queue.length - 1);
					lastVideoPlayed = playme;
					mapVideoElementToNowPlaying(queue.slider.queue[playme]);
					

				} else {
					if (lastVideoPlayed < queue.slider.options.numElements - 1) {
						lastVideoPlayed++;						
						mapVideoElementToNowPlaying(queue.slider.queue[lastVideoPlayed])
						
					} else {
						lastVideoPlayed = 0;
						mapVideoElementToNowPlaying(queue.slider.queue[0]);

					}
				}
				playVideo();				

			} else // queue box is closed
			{

				var current = $("#videogrid li[botrcode='"+player.botrCode+"']");

				if (current.next().length > 0) {
					
					prePlayVideo(current.next());
					
				} else {
					prePlayVideo(current.parent().children(":first"));
					
				}
			}

		}
	}
}
function initmodal() 
{
	
	$(".modalnav a").click(changeModalTab);
	$("#btfrmsend").click(sendMessage);
	$("#modalfrmembedcode").click( function() {
		this.select();
	});
	$("#mailsent").hide();
	$("#modalfrmsend").show();
	$("#frmcontact").submit( function() {
		$.post(baseUrl+"async/sendmail", {
			"from" :$("#tbfrmcontactemail").val(),
			"msg" :$("#frmcontactfeedback").val()
		}, {}, 'json');

		$("#frmcontact").fadeOut("fast", function() {
			$("#contactfrmsent").text("Thank you for contacting us.");
			$("#contactfrmsent").fadeIn("fast");
		});
		return false;
	});

	$(".modalshare .facebook").click(modalshare.facebook);
	$(".modalshare .digg").click(modalshare.digg);
	$(".modalshare .delicious").click(modalshare.delicious);
	$(".modalshare .myspace").click(modalshare.myspace);
	$(".modalshare .twitter").click(modalshare.twitter);

}
function sendMessage(e) 
{
	$.post(url("async/sharemail"), {
		"from" :$("#tbfrmemail").val(),
		"to" :$("#tbfrmtoemail").val(),
		"msg" :$("#frmsendtext").val()
	}, {}, 'json');

	$("#modalfrmsend").fadeOut("fast", function() {
		$("#mailsent").text("Your email is being validated and sent.");
		$("#mailsent").fadeIn("fast");
	});
	return false;
}
function changeModalTab(e) 
{
	openModalTab($(this));
	return false;
}


var modalshare = {
	facebook : function() {
		popup('http://www.facebook.com/sharer.php?u=' + getURL() + '&t='
				+ getHeadline(), 'facebook',
				'toolbar=0,status=0,height=436,width=646,scrollbars=yes,resizable=yes');
		return false;
	},

	digg : function() {
		popup('http://digg.com/remote-submit?phase=2&url=' + getURL()
				+ '&title=' + getHeadline() + '&bodytext=' + getDescription(),
				'digg',
				'toolbar=0,status=0,height=450,width=650,scrollbars=yes,resizable=yes');
		return false;
	},

	delicious : function() {
		popup('http://del.icio.us/post?v=4&partner=nyt&noui&jump=close&url='
				+ getURL() + '&title=' + getHeadline() + '&bodytext='
				+ getDescription(), 'delicious',
				'toolbar=0,status=0,height=400,width=700,scrollbars=yes,resizable=no');
		return false;
	},
	myspace : function() {
		popup('http://www.myspace.com/index.cfm?fuseaction=postto&u='
				+ getURL() + '&t=' + getHeadline() + '&c=' + getDescription(),
				'myspace',
				'toolbar=0,status=0,height=436,width=880,scrollbars=yes,resizable=yes');
		return false;
	},
	twitter : function() {
		popup('http://twitter.com/home?status=video+on+nomad+player+tv:+' + getURL(),
				'twitter',
				'toolbar=0,status=0,height=436,width=880,scrollbars=yes,resizable=yes');
		return false;
	}
};
function popup(url, name, params)
{
	var win = window.open(url, name, params);
}
function getURL() 
{
	var url = getVideoUrl(nowPlaying.title, currentChannel, nowPlaying.beid);
	
	return encodeURIComponent(url);
}
function getHeadline() 
{
	return encodeURIComponent(nowPlaying.title);
}
function getDescription() 
{
	return encodeURIComponent(nowPlaying.description);
}
function openModalTab(emt) 
{
	
	$("#modalfrmsend").show();
	$("#mailsent").hide();
	
	$("#vidBox").css("visibility","hidden");
	$(".modalnav li").removeClass('active');
	var className = emt.attr('class');
	$(".modalcontent div").hide();
	$("." + className.substr(0, className.length - 3)).show();

	emt.parent().addClass('active');

}
function tb_remove() 
{
	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	$("#TB_window").fadeOut(
			"fast",
			function() {
				$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload")
						.unbind().remove();
			});
	$("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {// if IE 6
		$("body", "html").css( {
			height :"auto",
			width :"auto"
		});
		$("html").css("overflow", "");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	$("#vidBox").css("visibility","visible");
	return false;

}
//ajax router
function pageload(hash)
{	
	var parts = ltrim(hash, '/').split("/");
	if (parts.length <= 1)
		badURL = true;			


		var beid = null;
		var needLoadPage = false;
		var loadPlaylist = function(){};
		var badURL = false;
		if (parts.length > 1)
		{
			if (parts[0] == "search")
				isSearch = "true";
			else
				isSearch = "";
			
			if (parts[1] != currentChannel)
			{
				needLoadPage = true;	
				var id = "#tab_"+parts[1].toLowerCase().replace(/ /,"");
				var id2 = "tab_"+parts[1].toLowerCase().replace(/ /,"");
				
				id = htmlentitiesDecode(id);
				id2 = htmlentitiesDecode(id2);
				changeChannel($(id), id2);
			}
			// chan/:channel
		}
		else
			badURL = true;
		if (parts.length > 2)
		{
			
			if (parts[2].toLowerCase() == "p")
			{
				if (parts[3] != currentPage)
					needLoadPage = true;

				currentPage = parts[3];
				
				//chan/:channel/p/:pageNumber
			}
			else
				badURL = true;
		}
		else
			badURL = true;
	// the case where we go from filtered pl to unflitered pl
	if (currentPlaylist != -1 && parts.length < 5)
	{
		currentPlaylist = -1;
		needLoadPage = true;
	}
		
	if (parts[0].toLowerCase() == "channel")
	{	
		if (parts.length > 5) // we have either a playlist or a video
		{
			if (parts[4].toLowerCase() == "pl")
			{
				if (parts[5] != currentPlaylist)
					needLoadPage = true;
				
				currentPlaylist = parts[5];

				//chan/:channel/p/:pageNumber/pl/:playlistId
			}
			else if(parts[4].toLowerCase() == "v")
				beid = parts[5];
				//chan/:channel/p/:pageNumber/v/:videoEncodedBaseId/:title
			else
				badURL = true;		
		}
		if (parts.length > 7) // we have a playlist and a video
		{
			if (parts[6] == "v")
				beid = parts[7]; 
				//chan/:channel/p/:pageNumber/pl/:playlistId/v/:videoEncodedBaseId/:title
			else
				badURL = true;

		}

	}	
	else if(parts[0].toLowerCase() == "search")
	{
		if (parts.length > 5) // we have either a search query
		{
			
			var search = decodeURIComponent(parts[5]);

			if (search != searchQuery)
				needLoadPage = true;
			
			searchVideos(search);
		}
		else
			badURL = true;
		
		if (parts.length > 7) // we have a search query and a video
		{
			if (parts[6] == "v")
				beid = parts[7];
		}
		
		
	}
	
	if (badURL)
	{
		//console.log("bad URL!");;
		beid = currentBeid;
		var emt = $("#videogrid li[botrcode='" + beid + "']");
		mapVideoElementToNowPlaying(emt);
		setTimeout(playVideo, 500);
	}	
	else
	{
		if(beid != null && !needLoadPage)
		{
			var emt = $("#videogrid li[botrcode='" + beid + "']");
			mapVideoElementToNowPlaying(emt);
			playVideo();
							
		}
		else if (beid != null && needLoadPage)
		{
			loadPage(function()
					{
						if (!isPlayingVideo)
						{
							mapVideoElementToNowPlaying($("#videogrid li[botrcode='" + beid + "']"));
							playVideo();
						}
					});
		}
		else if(beid == null && needLoadPage)
		{
			loadPage(function()
					{
						if (!isPlayingVideo)
						{
							mapVideoElementToNowPlaying($("#videogrid").find(":nth-child(1)"));
							playVideo();
						}
						
					});
		}
		
	}
}

//decode les htmlentities
function htmlentitiesDecode(str)
{
	//add here your special char to decode
	str = str.replace('%c2%a2', '¢');
	
	return str;
}

function initGridListeners()
{
	//tooltip
	var i = 1;
	$('#categorylist ul li').each(function()
	{
		if (i % 6 == 0 || i == 5 || i == 11 || i == 17 || i == 23  ) // last 2 rows flipped
		{
			$(this).tooltip({delay: 0 ,track: true,showBody: true,positionLeft: true,left: -520,top: -40,bodyHandler: function() {
		        return "<div style='display:block' class='hovervideopopupright'>"+$(this).find(".hovervideopopup").clone().html()+"</div>";
		    }, showURL: false });
		}
		else
			$(this).tooltip({delay: 0 ,track: true,showBody: true,left: -70,top: -40,bodyHandler: function() {
		        return "<div style='display:block' class='hovervideopopup'>"+$(this).find(".hovervideopopup").clone().html()+"</div>";
		    }, showURL: false });
		i++;
	});
	

	//videogrid
	$('#categorylist ul li a.addtoqueue').click(function(e){ addToQueue($(this).parent().parent().parent()); return false; });
	$('#categorylist ul li').click(function(e){	prePlayVideo($(this));	return false; });	
	$('#categorylist ul li').mouseover(function(e) {$(this).addClass("hover");$(this).find(".hovervideooverlay").show();});
	$('#categorylist ul li').mouseout(function(e) {$(this).removeClass("hover");$(this).find(".hovervideooverlay").hide();});

	$('.addall').click(addallToQueue);

	$('.rss').click(function()
		{
			if (currentPlaylist != -1)
				window.location.href = 'rss/' + currentChannel + '/' + currentPlaylist;
			else
				window.location.href = 'rss/' + currentChannel + '/';
		});

	$('.podcast').click(function()
		{
			if (currentPlaylist != -1)
				window.location.href = 'itpc://' + host + '/podcast/' + currentChannel + '/' + currentPlaylist;
			else
				window.location.href = 'itpc://' + host + '/podcast/' + currentChannel + '/';
		});
	
	$('.global-podcast,.podcast').tooltip({delay: 0 ,track: true, showBody: true, positionLeft: true, showURL: false });
}
function initSearch()
{
	$("#tabsearch").submit(function()
			{
				var search = $("#tabtbsearch").val();	
				$.historyLoad("search/"+currentChannel+"/p/"+currentPage+"/q/"+encodeURIComponent(search));
				return false;
			});
	$('#categorytabs .search a').click(function() {
		currentChannel = searchChannel;
		var search = $("#tabtbsearch").val();	
		$.historyLoad("search/"+currentChannel+"/p/"+currentPage+"/q/"+encodeURIComponent(search)); 				
		return false;
	});	
}
function initAjaxHistory()
{
	// url history
	$.historyInit(pageload);
	// set onlick event for buttons
	$("a[rel='history']").click(function(){
		var hash = this.href;
		hash = hash.replace(/^.*#/, '');
		$.historyLoad(hash);
		return false;
	});
}
function initChannel()
{
	$("#tvqueuecontrols .deleteall").click(clearQueue);
	$("#tvqueuecontrols_options .shuffle").click(toggleShuffleQueue);
	$("#tvqueuecontrols .myqueue").click(toggleMyQueue);
}
function initPagination()
{
	$('.paginationprev').click(function(e){getprevpage();return false;});
	$('.paginationnext').click(function(e){getnextpage();return false;});	
}
function initPlaylist()
{
	$("#playlistDDL").click(function(e){ togglePlaylist();return false;});	
}
function makeScrollable(entryWrapper)
{
	var entry = entryWrapper.find('.description');
	var scrollHandle = entryWrapper.find('.entry-scroll-handle');
	var scrollHandleHeight = scrollHandle.height();
	var entryHeight = entry.height();
	var scrollStart = parseInt(entryWrapper.css('padding-top'));
	var ratio, maxTop, entryWrapperHeight;
	
	entryWrapperHeight = entryWrapper.height();
	ratio = (entryHeight - entryWrapperHeight) / (entryWrapperHeight - scrollHandleHeight);
	maxTop = entryWrapperHeight - scrollHandleHeight + scrollStart;
	
	if (entryWrapperHeight < entryHeight) {
		scrollHandle.css('display', 'block');
	} else {
		scrollHandle.css({'display': 'none', 'top': scrollStart});
		entry.css('top', 0);
	}
	
	var scrollTo = function() {
		var entryWrapper = $('#tvdesc .description-wrapper');
		var entry = entryWrapper.find('.description');
		var scrollHandle = entryWrapper.find('.entry-scroll-handle');
		var scrollHandleHeight = scrollHandle.height();
		var entryHeight = entry.height();
		var scrollStart = parseInt(entryWrapper.css('padding-top'));
		var ratio, maxTop, entryWrapperHeight;
		
		entryWrapperHeight = entryWrapper.height();
		ratio = (entryHeight - entryWrapperHeight) / (entryWrapperHeight - scrollHandleHeight);
		maxTop = entryWrapperHeight - scrollHandleHeight + scrollStart;
		
		var y = parseInt(scrollHandle.css('top'));
		entry.css('top', -(y - scrollStart) * ratio);
	};
	
	scrollHandle.css('top', scrollStart);
	scrollHandle.draggable({
		axis: 'y',
		containment: 'parent',
		drag: function(event, ui) {
			scrollTo();
		}
	});
	
	entryWrapper.mousewheel(function(e, d) {
		if (entryWrapperHeight > entryHeight) {
			return;
		}
		
		var y = parseInt(scrollHandle.css('top')) - 20 * d;
		if (y < scrollStart) {
			y = scrollStart;
		} else if (y > maxTop) {
			y = maxTop;
		}
		scrollHandle.css('top', y);
		scrollTo();
	});
}