// --------- ( page-specific javascript calls )---------
var listingsMenu = null;
var tempText;
var windowHeight, headerHeight, loginBoxHeight, footerHeight;
var queryStr = window.location.search.substring(1);

// put global network site array here, so it can be auto generated from db later
var networksites = new Array();
networksites[10]="cbs.com";
networksites[11]="fox.com";
networksites[12]="abc.go.com";
networksites[13]="nbc.com";
networksites[14]="thewb.com";
networksites[15]="pbs.org";
networksites[16]="cwtv.com";
networksites[17]="usanetwork.com";
networksites[18]="fxnetworks.com";
networksites[19]="tnt.tv";
networksites[20]="tbs.com";
networksites[21]="mylifetime.com";
networksites[22]="bravotv.com";
networksites[23]="aetv.com";
networksites[24]="amctv.com";
networksites[25]="comedycentral.com";
networksites[26]="syfy.com";
networksites[27]="spike.com";
networksites[28]="mtv.com";
networksites[29]="vh1.com";
networksites[38]="abcfamily.go.com";
networksites[39]="nick.com";
networksites[40]="nicktoons.nick.com";
networksites[41]="teennick.com";
networksites[42]="nickjr.com";
networksites[43]="cartoonnetwork.com";
networksites[44]="disney.go.com";
networksites[45]="disney.go.com/disneyxd";
networksites[46]="disney.go.com/playhouse";
networksites[57]="adultswim.com";
networksites[58]="pbskids.org";
networksites[98]="hulu.com";
networksites[99]="zshare.net";
networksites[100]="vidxden.com";

function SendFBMessage(subject, message)
{
	var url = "http://www.facebook.com/?compose=1&subject="+subject+"&message="+message+"&sk=messages&action=www.google.com";
	window.open (url, 'Send Recommendation', 'height=480,width=640,modal=yes,alwaysRaised=yes');
}

var PlayEpisode = function(episode)
{
//	var episodeId = episode.attr('episodeId');
	var seriesId = episode.attr('seriesId');
	var episodeUrlId = episode.attr('urlId');
	var url = '/web/episode.play.php?episodeUrlId='+episodeUrlId;

	$('#viewbar').show();  // Use show instead of slideDown to eliminate timing glitch that shows up in redirect links
	$('#report').attr("episodeUrlId", episodeUrlId);
	$('#reload').attr("url", url);
	
	// check to see if this series is already on the favorites list
	// if it is, disable the "add to favorites" button when playing the episode
	if($('#favorites').find('.favshow').is("[seriesId="+seriesId+"]")) {
		$('#addfav').attr("seriesId", seriesId).attr('disabled', 'disabled').addClass('disabled');
	}
	else {
		$('#addfav').attr("seriesId", seriesId).removeAttr('disabled').removeClass('disabled');
	}
	parent.document.body.rows="35px,*";
	parent.viewer.location=url;
	listingsMenu.lockMenu(); // Don't capture keystrokes while video is playing
	return (false);
};

// This is a separate function because it gets called whenever the favorites are reloaded 
function MakeFavoritesDraggable() {
	$('ul.favorites a.episode').draggable({ 
		helper: 'clone', 
		addClasses: false, 
		revert: true, 
		appendTo: 'body',
		distance: 10,
		start: function(event, ui) { ui.helper.css({ width: $(this).width()*1.2, padding: "0.2em 0.5em", background: "#345", border: "1px solid #acf", textDecoration: "none", opacity: "0.35" }); }
	});
// Reload the cluetip behavior for all elements in the favorite box
	$('ul.favorites .cluetip').cluetip({
		splitTitle: '|',
		arrows: true, 
		dropShadow: true,
		leftOffset: 20,
	    hoverIntent: {    
			sensitivity:  3,
			interval:     150,
			timeout:      0
		}
		,cluetipClass: 'jtip'
	});
};

// Size the favorites box
function ResizeFavorites() {

	f = $('#favorites');
	var margin = f.verticalMargin();
	var padding = f.verticalPadding();
	var parentExtra = f.parent().verticalMargin() + f.parent().verticalPadding();
	var extra = 13;
	var fHeight = windowHeight-headerHeight-loginBoxHeight-footerHeight-margin-padding-parentExtra-extra;
	f.height(fHeight);
	//alert ("windowHeight:"+windowHeight+"\nvMargin:"+margin+"\nvPadding:"+padding+"\nheaderHeight:"+headerHeight+"\nloginBoxHeight:"+loginBoxHeight+"\nfooterHeight:"+footerHeight+"\nextra:"+extra+"\n\nFinalHeight:"+fHeight);
	
	var u = $('#favorites ul.favorites');
	var innerHeight = f.trueInnerHeight();
	var titleHeight = f.children('.title').outerHeight(true);
	margin = u.verticalMargin();
	padding = u.verticalPadding();
	extra = 0;
	var uHeight = innerHeight-titleHeight-margin-padding-extra; 
	u.height(uHeight);
	
	//alert ("OuterHeight:"+fHeight+"\nInnerHeight:"+innerHeight+"\ntitleHeight:"+titleHeight+"\npadding:"+padding+"\nextra:"+extra+"\n\nFinal Height:"+uHeight);
}	

function ResizeMenu() {
	listingsMenu.resize(windowHeight-headerHeight-footerHeight - 33);
}

function ResizeSidekick() {
	var s = $('#sidekick');
	var sHeight = windowHeight-headerHeight-footerHeight - 21; 
	s.height(sHeight);

	// set body size and make overflow hidden (so if you scroll, the header doesn't scroll w. it, just the body)
	// for multiple body fields, loop through
	var bgroup = s.find('div.briefs div.body');
	var bnum = bgroup.length;
	bgroup.each(function(){
		var b = $(this);
		var p = (b.outerHeight(true)-b.trueInnerHeight()); // padding
		var bHeight = (sHeight / bnum) - (bgroup.first().offset().top-s.offset().top) - p - 3;
		b.height(bHeight);
	});
}

/* view = channels, shows, favorites, search
** postData = key1=val1&key2=val2...&keyn=valn  (necessary for facebook app, appends fbUserId to the document query str)
** username = <string>, optional
**/
function LoadListings(view, postData, mode, userName)
{
	// Set default crumbText
	var crumbText;
	var topText;
	var seriesId = null;
	var epId = null;
	var errorText = null;
	var viewArgs = view.split("|");
	view = viewArgs[0];
	var listingUrl = "/web/svc.listings.by"+view.toLowerCase()+".php";
	view = view[0].toUpperCase()+view.substring(1);
	switch (view) {
		case 'Search':
			crumbText = "All Search Results";
			break;
		case 'Favorites':
			if (userName == null || userName == undefined) {
				crumbText = "My Favorites";
				errorText = "You have not saved any Favorite shows yet.  Browse the TV listings by <b class='strong'>Channels</b> or by <b class='strong'>Shows</b>, and save the shows you like into your Favorites list for quick access.";
			} else {
				crumbText = userName + "'s Favorites";
				errorText = userName + " has not saved any Favorite shows yet";
			}
			topText = crumbText;
			if (mode == "fav")
			{
				seriesId = "[seriesId="+postData+"]";
			}
			break;
		case 'Channels':
			crumbText = "All Channels";
			topText = "Channels";
			break;
		case 'Shows':
			crumbText = "All Shows";
			topText = "Shows";
			break;
		case 'Top':
			crumbText = "Popular Shows";
			topText = "Popular";
			var loc = postData.indexOf(",");
			seriesId = "[seriesId="+postData.substr(0, loc)+"]";
			postData = "ids="+postData.substr(loc+1);
			break;
		case 'Rec':
			crumbText = "Recommended Shows";
			topText = "Recommended";
			var loc = postData.indexOf(",");
			seriesId = "[seriesId="+postData.substr(0, loc)+"]";
			postData = "ids="+postData.substr(loc+1);
			listingUrl = "/web/svc.listings.bytop.php";
			break;
		case 'Episodelist': //now redundant with by Series, may remove soon
			postData = "seriesid="+viewArgs[1];
			crumbText = viewArgs[2];
			break;
		case 'Series':
			var stitle;
			var sid;
			// This assumes that the postData has "seriesId=<seriesId>" and seriesTitle='title'
			stitle = FindQueryString(savedQueryString, "seriesTitle");
			if(stitle) crumbText = stitle;
			else crumbText = "Series";
			topText = "Series";
			// create jQuery attribute search filter
			sid = FindQueryString(savedQueryString, "seriesId");
			postData = "seriesid="+sid;
			epId = FindQueryString(savedQueryString, "epId");
			if(epId) epId = "[epId="+epId+"]";
			listingUrl="/web/svc.listings.byepisodelist.php";
			break;
		default:
			crumbText = "All "+view;
	}
	
	if (mode != "fb") {
		errorText = null;
	}
	// Ajax call to load the listings
	$.ajax({
		url: listingUrl,
		dataType: "json",
		data: postData,
		type: "post",
		error: function(xml, status, error) { alert (error); },
		success: function(resp, status) {
					if (resp.code != 1) {
						//$.prompt(resp.msg);
						if (!errorText) errorText = resp.msg; 
						resp.listings="<ul class='strong ui-corner-all'><div style='margin: 2em 1em; text-align:center;'>"+errorText+"</div></ul>";
					}
					if (listingsMenu) listingsMenu.kill();
					listingsMenu = new Menu($('#abc'), {
						content: resp.listings,
						backLink: false,
						crumbDefaultText: crumbText,
						topLinkText: topText,
						showSpeed: 100, // show/hide speed in milliseconds
						crossSpeed: 300, // cross-fade speed for multi-level menus
						width: 400, // width of menu container, must be set or passed in to calculate widths of child menus
						maxHeight: windowHeight-headerHeight-footerHeight-33 // max height of menu (if a drilldown: height does not include breadcrumb)
						//,positionOpts: { posX: 'left', posY: 'top', directionV: 'bottom', directionX: 'right' }
					});
					listingsMenu.showMenu();

					if(seriesId) {
// Need timeout here because menu setup has delayed completion for performance reasons, timeout is hardcoded as can't think of simple way to access internal timeout in menu setup
						setTimeout(function(){
							$('#fg-menu-container').find(".serie").filter(seriesId).click(); 
						}, 220);
//Timeout needs to stay correlated with Menu crossSpeed, can't figure out simple way to do that here so hardcoded 220
						setTimeout(function(){
							$('#fg-menu-container').find(".serie").filter(seriesId).next().find('a:first').trigger('mouseover');
						}, 440);
					}
					
					if(epId) {
						setTimeout(function(){
							var epmenu = $('#fg-menu-container').find('.episodelist');
							if(epmenu.length) {
								var epitem = epmenu.find('a').filter(epId);
								if(epitem.length) {
									var scrolldiff = epitem.offset().top - epmenu.offset().top;
									epmenu.scrollTop(scrolldiff).find('a').filter(epId).trigger('mouseover');
								} else {
									epmenu.find('a:first').trigger('mouseover');
								}
							}
						}, 440);
					} 
				}
	});	
	
}

/* ---------------------( Document Ready )----------------------*/

$(function() {

	windowHeight = $(window).height();
	headerHeight = $('#header').outerHeight(true);  // includes height, padding, border, margin
	if (headerHeight > 45) headerHeight = 45;   // Cap at 45px to get around IE bug where it oversizes
	footerHeight = $('#footer').outerHeight(true);
	loginBoxHeight = $('#login').outerHeight(true);

	// Hide the viewbar, there seems to be some kind of browser bug which sometimes reverts the viewbar back to default state (hidden), so change the default state
	$('#viewbar').hide(); // There seems to be some kind of timing glitch which causes menu to be offscreen if this is done too fast
	
	
	// Load top shows
	/*
	$.ajax({
		url: "/web/svc.listings.top.php",
		dataType: "json",
		beforeSend: null,
		complete: null,
		success: function(resp, status) {
					if (resp.code != 1) {
						resp.listings="<ol class='errmsg bigtext'>"+resp.msg+"</ol>";
					} 
					var t = $('#topshows').children('.body'); 
					t.html(resp.listings);
					t.find('.episode').draggable({ 
						helper: 'clone', 
						addClasses: false, 
						revert: true, 
						appendTo: 'body',
						start: function(event, ui) { ui.helper.css({ width: $(this).width()*1.2, padding: "0.2em 0.5em", background: "#345", border: "1px solid #acf", textDecoration: "none", opacity: "0.35" }); }
					});
				}
	});
	*/
	// Load listings on initial page load
	LoadListings(by, queryStr+"&keywords="+$("#searchform input.textbox").val());
	
	// Load listings on main menu item selection (by channel, show, favorites)
	$("li a", "#mainmenu").click(function() {
		var t = $(this);
		LoadListings(t.attr("view") , queryStr);
		t.parent("li").addClass("highlight").siblings("li").removeClass("highlight");
		return (false);
	});
	
	// Load listings search
	$("#searchform").submit(function() {
		var t = $(this);
		var textbox = t.children("input.textbox");
		LoadListings(t.attr("view"), queryStr+"&"+textbox.attr("name")+"="+textbox.val());
		t.closest("li").addClass("highlight").siblings("li").removeClass("highlight");
		return (false);
	});
	
	// Load episodes of specific show
	$('a.show').live('click', function() {
		var t = $(this);
		LoadListings(t.attr("view"), queryStr+"&seriesid="+t.attr("seriesId"), t.attr("seriesTitle"));
		t.parents(".main").siblings("#header").children("#mainmenu").find("li").removeClass("highlight");
		return (false);
	});
	
	// Load top shows list, then click through to episodes of specific show
	$('a.topshow').live('click', function() {
		var t = $(this);
		var ids = new Array();
		ids.push(t.attr("seriesId"));
		t.parent().parent().find(".topshow").each(function(){
			ids.push($(this).attr("seriesId"));
			});
		LoadListings(t.attr("view"), ""+ids);
		t.parents(".main").siblings("#header").children("#mainmenu").find("li").removeClass("highlight");
		return (false);
	});

	// Load favorites list, then click through to specific show
	$('a.favshow').live('click', function() {
		var t = $(this);
		LoadListings(t.attr("view"), t.attr("seriesId"), "fav");
		t.parents(".main").siblings("#header").find("[view='favorites']").parent("li").addClass("highlight").siblings("li").removeClass("highlight");
		return (false);
	});

	// Navigate to show url on episode selection
	$('a.episode').live('click', function() {
		PlayEpisode($(this));
		return (false);
	});
	
	// Prompt user to send a note to a friend when they click on the "recommend" icon
	$('.favorites div.recommend').live('click', function() {
		
	});
	
	// Keep the viewbar at the top of the page
	$(parent.browser).scroll(function() {
		$('#viewbar').css({top: $(window).scrollTop()+"px" });
	});
	
	// Report broken link
	$('#report').click(function() {
		$.ajax({
			url: '/web/svc.episode.report.php',
			dataType: 'json',
			type: 'post',
			data: { episodeUrlId: $(this).attr('episodeUrlId') },
			beforeSend: function() { return (true); },
			success:
				function(resp, status) {
					$('#return > a').trigger('click');
					$.prompt('Thank you for reporting the broken link');
				}
		});
	});
	
	// Reload show in viewer frame
	$('#reload').click(function() {
		var url = $(this).attr("url");
		parent.viewer.location = url;
	});
	
	// Add current show to favorites list
	$('#addfav').click(function() {
		var seriesId = $(this).attr('seriesId');
		$.ajax({
			url: '/web/svc.user.addfavorite.php',
			beforeSend: null,
			dataType: 'json',
			type: 'post',
			data: { seriesId: seriesId },
			success:
				function(resp, status) {
					var b = $('#favorites').children('div.body:first');
					b.children(/*'ul.favorites'*/).remove();
					b.append(resp.favorites);
					ResizeFavorites();
					MakeFavoritesDraggable();
					// disable button
					$('#addfav').attr('disabled', 'disabled');
					$('#addfav').addClass('disabled');
				}
		});
	});

	// Return to channelhop
	$('#return > a').click(function() {
		parent.viewer.location="http://www.channelhop.com/web/blank.html";
		parent.document.body.rows="*,0";
		$('#viewbar').slideUp(); // There seems to be some kind of timing glitch which causes menu to be offscreen if this is done too fast
		$('.fg-menu-current .li-hover').focus().trigger('mouseover');
		listingsMenu.unlockMenu();  // Unlock the keyboard shortcuts for the menu
	});

	// Keep the menu maximied to size of browser when the browser is resized
	// But only set the callback after everything has loaded so that it doesn't get 
	// called on window load (since we already resize favorites/sidekick explicitly below)
	// IE calls this on window load otherwise (but firefox doesn't)
	setTimeout(function() {
		$(window).resize(function() {
			windowHeight=$(window).height();
			if (typeof(listingsMenu) == 'object') ResizeMenu();
			ResizeSidekick();
			ResizeFavorites();
		});
	}, 1000);

	// Resize favorites and sidekick on initial window load
	ResizeFavorites();
	ResizeSidekick();
	// $('#fg-menu-container').height(windowHeight-headerHeight-32); // initial size
	
	// Make the favorites box accept drop of a show
	$('#favorites').droppable({
		activeClass: 'droppable-active',
		hoverClass: 'droppable-hover',
		accept: '.fg-menu .serie, .fg-menu .episode, .sidekick .episode',
		tolerance: 'touch',
		drop: function(event, ui) {  
				var t = $(this);
				var seriesId = ui.helper.attr('seriesId');
				//alert(seriesId);
				if (t.find("a[seriesId='"+seriesId+"']").size() > 0) return;
				$.ajax({
					url: '/web/svc.user.addfavorite.php',
					dataType: 'json',
					type: 'post',
					data: { seriesId: seriesId },
					success:
						function(resp, status) {
							var b = t.children('div.body:first');
							b.children(/*'ul.favorites'*/).remove();
							b.append(resp.favorites);
							ResizeFavorites();
							MakeFavoritesDraggable();
						}
				});
				ui.draggable.draggable('option', 'revert', false);
				setTimeout(function() { ui.draggable.draggable('option', 'revert', true); }, 1000);
			}
	});
	// Make the trash can in favorites box accept drop of a show
	$('#favorites .trash').droppable({
		activeClass: 'droppable-active',
		hoverClass: 'droppable-hover',
		accept: '.favorites .episode',
		tolerance: 'touch',
		drop: function(event, ui) {  
				ui.draggable.prev().trigger('click');
				ui.draggable.draggable('option', 'revert', false);
			}
	});
	MakeFavoritesDraggable();

	// Callback that removes a show from Favorites
	$('#favorites .remove').live('click', function() {
		var t = $(this).closest('div.body');
		var seriesId = $(this).next().attr('seriesId');
		$(this).mouseout();		// Needed to hide cluetip before refreshing window
		//alert(seriesId);
		//if (t.find("li[seriesId='"+seriesId+"']").size() == 0) return;
		$.ajax({
			url: '/web/svc.user.removefavorite.php',
			dataType: 'json',
			type: 'post',
			data: { seriesId: seriesId },
			success:
				function(resp, status) {
					t.children('ul.favorites').remove();
					t.append(resp.favorites);
					ResizeFavorites();
					MakeFavoritesDraggable();
				}
		});
	});
	
	//Show e-mail message recommendation box
	//If title in e-mail box is desired, can append in $.prompt call before $('#msgdiv').html()
	$('#favorites .recmsg').live('click', function() {
		var seriesId = $(this).attr('seriesId');
		var seriesTitle = $(this).attr('seriesTitle');
		SendEmailRec(seriesId, seriesTitle);
		return (false);
	});
	
});