// levitt.tv
// JavaScript functions using jquery to build video player choices
// By Greg Hartwig (webmaster at levitt dot com)
// 2007-11-05

// Set up basic movie player layout
//var flvStd = new SWFObject("/player/player5-licensed.swf","player",320,240+mediacontrol_height,"9.0.115","#FFFFFF", "high");
var playdataStd = {flashplayer: "/player/player-licensed.swf", width: 320, height: 240+mediacontrol_height, allowfullscreen: "true", controlbar: "bottom"};
playdataStd["config"] = path_tv+"/player/config_std.xml";
playdataStd["skin"]   = path_tv+"/player/"+mediaplayer_skin+".zip";


/*
var playdataGoogle = new SWFObject("http://video.google.com/googleplayer.swf","player",320,240+mediacontrol_height_google,'9.0.115','#FFFFFF', 'best');
playdataGoogle.addVariable("hl", "en");
playdataGoogle.addParam("allowfullscreen","true");

var playdataTangle = new SWFObject("http://www.tangle.com/flash/swf/flvplayer.swf","player",320,240+mediacontrol_height_google,'9.0.115','#FFFFFF', 'best');
playdataTangle.addParam("wmode","transparent");
playdataTangle.addParam("quality", "high");
// <embed src="http://www.tangle.com/flash/swf/flvplayer.swf" FlashVars="viewkey=85b5a25f333e5ce7f3f4" wmode="transparent" quality="high" width="330" height="270" name="tangle" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></embed>
*/
gPlayerNum = 0;



// Pre-load buy/play images
$(document).ready(function() {
	buylinks  = $("img.buylink");
	playlinks = $("img.playlink");
	
	// Pre-load, if needed
	if (buylinks) {
		var img_buy= new Image(); 
		img_buy.src="/pics/buy";
		var img_buyover= new Image(); 
		img_buyover.src="/pics/buy-over";

		$(buylinks)
		.mouseover(function() {
			this.src = img_buyover.src;
		})
		
		.mouseout(function() {
			this.src = img_buy.src;
		});
	}


	if (playlinks) {
		var img_play= new Image(); 
		img_play.src="/pics/play";
		var img_playover= new Image(); 
		img_playover.src="/pics/play-over";
		
		$(playlinks)
		.mouseover(function() {
			this.src = img_playover.src;
		})
		
		.mouseout(function() {
			this.src = img_play.src;
		});
	}


	
});



function makeChoices(prodnum, idval) {
	if (!idval) idval="V"+prodnum;
	var msgboxid  = "choices-"+idval;
	
	// If it's showing already, hide it
	if ($("#"+msgboxid+":visible").is("div")) {
		hideChoices(idval, msgboxid)
	} else {
		showChoices(prodnum, idval, msgboxid);
	}
	
	return false;
}



function loadChoices(prodnum, idval, msgbox) {
	//$(msgbox).show('normal');  // "Loading..." message won't show without this, but it's smoother this way

	// Get the data about the program from the server
	$.ajax({
		url: '/bin/proginfo.php',
		type: "get",
		data: {prodnum: prodnum},
		
		error: function() {
			$(msgbox).html("<!-- STATUS:ERROR --><i><small>Error:  Try again later.<"+"/small><" + "/i>").show('normal');
		},
		
		success: function(xml) {
			var flvGoogle = $("Media > googleid" ,xml).text();
			var flvfile   = $("Media > flvfile"  ,xml).text();
			var flvsize   = $("Media > flvfile"  ,xml).attr('size');
			var mp4size   = $("Media > mp4file"  ,xml).attr('size');
			var preview   = $("Media > preview"  ,xml).text();
			var mp4file   = $("Media > mp4file"  ,xml).text();
			var rmfile    = $("Media > rmfile"   ,xml).text();
			var youtube   = $("Media > youtube"  ,xml).text();
			var capfile   = $("Media > capfile"  ,xml).text();
			var txt = "<!-- STATUS:OK -->Choose format:\n" + 
						 "<ul class=\"compact\">\n";
			
			if ( rmfile || mp4file || flvfile || flvGoogle || youtube) {
				var doFlvArgs;
				
				if (mp4file)
					vsize = mp4size;
				if (flvfile)
					vsize = flvsize
				
				if (flvGoogle)
					doFlvArgs = "'"+idval+"',{flvfile:'"+flvGoogle+"',mp4file:'"+mp4file+"',preview:'"+preview+"',capfile:'"+capfile+"'},'320x240',true";
				else if (flvfile || mp4file)
					doFlvArgs = "'"+idval+"',{flvfile:'"+flvfile+"',mp4file:'"+mp4file+"',preview:'"+preview+"',capfile:'"+capfile+"'},'"+vsize+"',false";

				if (doFlvArgs)
					txt += "<li><a href=\"#\" onclick=\"return doFlv("+doFlvArgs+");\" title=\"Best for most&#8212;plays video in your browser or full-screen\">Play Flash<"+"/a> (in your browser)<"+"/li>";

				if (mp4file)
					txt += "<li><a href=\""+path_tv+mp4file+"?pl\" target=\"mp4window\" title=\"Best for iPhone or no Flash&#8212;plays in a new browser window\">Play MP4<"+"/a> (Quicktime) <a href=\""+path_tv+"/download"+mp4file+"?dl\" title=\"Download MP4 movie to your computer\">download MP4</a><"+"/li>";

				if (rmfile)
					txt += "<li><a href=\""+path_tv+rmfile+"\" title=\"Best for slow connections&#8212;plays outside of your browser\">Play RealMedia<"+"/a> (RealPlayer)<"+"/li>";
			} else {
				txt = "<i><small>No media available for this program.<"+"/small><" + "/i>";
			}
			
			$(msgbox).html(txt).show('normal');
		}
	});
}
// {name1:"hello",name2:"world",name3:"foobar"}


function doFlv(idval, files, vidsize, isGoogle) {
	//vidsize = "320x240";   // #################################  KEEP FROM CHANGING PLAYER HEIGHT (for now)
	var playerid = "player-"+idval;
	if ($("#"+playerid).is("div")) {
		hidePlayer(idval, playerid);
	} else {
		showPlayer(idval, playerid, files, vidsize, isGoogle);
	}
	return false;  // Keep browser on the page
}



function showPlayer(idval, playerid, files, vidsize, isGoogle) {
	var msgboxid  = "choices-"+idval;
	var msgbox = $("#"+msgboxid);
	$(msgbox).append("<div id=\""+ playerid +"\" class=\"playwindow\"><"+"/div>");
	var playerobj = $("#"+playerid);
	var flv, control_height;
	var video_width, video_height;
	
	// Get video width/height
	if (vidsize == "")
		vidsize = "320x240";
	var t = vidsize.match(/(\d+)x(\d+)/);
	video_width  = t[1]-0;  // Convert to a number
	video_height = t[2]-0;
	
	if (isGoogle) {
		flv = flvGoogle;
		control_height = mediacontrol_height_google;
	} else {
		flv = flvStd;
		control_height = mediacontrol_height;
	}
	//console.log("vidsize="+vidsize+", vwidth="+video_width+",vheight="+video_height+", player_h="+(video_height+control_height));
	
	// Set video size
	flv["displaywidth"]  = video_width;
	flv["displayheight"] = video_height;
	
	// Set player size
	flv["width"]  = video_width;
	flv["height"] = video_height + control_height;
	

	// Set DIV size
	$(playerobj).width(video_width);
	$(playerobj).height(video_height + control_height);
	
	player_id = "player-" + (++gPlayerNum);  // Not used??
	
	if (isGoogle) {
		flv["docId"] = files.flvfile;
	} else {
		// flv and/or mp4:
		flv["image"] = path_tv + files.preview;
		if (files.capfile) {
			flv["captions.file"] = path_tv + files.capfile;
			flv["plugins"]       = "captions-1";
		}
		
		// mp4:
		if (files.mp4file != '') {
			flv["file"]        = path_tv + files.mp4file;
			if (files.flvfile)
				flv["fallback"] = path_tv + files.flvfile;
			else
				delete flv["fallback"];  // If we just set it to null, it doesn't work.
		} else {
			// flv only:
			flv["file"] = path_tv + files.flvfile;
			delete flv["fallback"];
		}
	}
	
	$(playerobj).show('normal', function() {
      jwplayer(playerid).setup(flv);
	});
}



function hidePlayer(idval, playerid) {
	var playerobj = $("#"+playerid);
	if ($(playerobj).is("div"))
		$(playerobj).empty().hide('normal', function() {
			$(playerobj).remove();
		});
}



function showChoices(prodnum, idval, msgboxid) {
	var msgbox;
	
	// If the div does not exists, create it
	if (!$("#"+msgboxid).is("div"))
		$("#"+idval).append("<div id=\"" + msgboxid + "\" class=\"choices\"><i><small>Loading...<"+"/small><" + "/i><"+"/div");
	
	msgbox = $('#'+msgboxid);
		
	// If msgbox contains "STATUS:OK" then just show it, otherwise load it
	if ($(msgbox).html().indexOf("STATUS:OK") == -1)
		loadChoices(prodnum, idval, msgbox);
	else
		$(msgbox).show('normal');
}



function hideChoices(idval, msgboxid) {	
	//hidePlayer(idval);
	$("#"+msgboxid).hide('normal');
}









// Just show the player window (for individual video pages)
function showPlayerWindow(playerid, files, vidsize, dummy) {
	var playdata, control_height;
	
	// Change width if on iPhone/iPod
	//alert("on="+on_iPhone+", for="+for_iPhone);
	if (for_iPhone) {
		var t = vidsize.match(/(\d+)x(\d+)/);
		var w = t[1]-0;  // Convert to a number
		var h = t[2]-0;
		
		h = 290 * (h / w);
		///////////////////////////////////////////////////////vidsize = "290x" + h.toFixed();
	}

	
	// Get video width/height
	if (vidsize == "")
		vidsize = "320x240";
	var t = vidsize.match(/(\d+)x(\d+)/);
	var video_width  = t[1]-0;  // Convert to a number (must use -0 because +0 can append a "0")
	var video_height = t[2]-0;
	
	playdata = playdataStd;
	control_height = mediacontrol_height;
	
	// Set video size
	playdata["displaywidth"]  = video_width;
	playdata["displayheight"] = video_height;
	
	// Set player size
	playdata["width"]  = video_width;
	playdata["height"] = video_height + control_height;
	
	// Preference order:  Youtube, mp4, flv
	if (files.youtube) {
		playdata["file"] = "http://www.youtube.com/watch?v=" + files.youtube;
		playdata["provider"] = "youtube";
	} else
	if (files.mp4file) {
		playdata["file"] = path_tv + files.mp4file;
		if (files.flvfile)
			playdata["fallback"] = path_tv + files.flvfile;
	} else {
		// flv only:
		playdata["file"] = path_tv + files.flvfile;
	}
	
	playdata["image"] = path_tv + files.preview;
	if (files.capfile) {
		playdata["captions.file"] = path_tv + files.capfile;
		playdata["plugins"]       = "captions-2";
	}
	
	
   jwplayer(playerid).setup(playdata);
}





// Play video from a specific spot
function video_jump(id, secs) {
	var doSeek=true; 
	var state = jwplayer(id).getState();
	if ("IDLE" == state)  // Player is stopped (BUFFERING, PLAYING, PAUSED, IDLE)
		jwplayer(id).setMute(true).play(true).onPlay(function() {if (doSeek) {doSeek=false; jwplayer(id).pause(true).setMute(false).seek(secs).play(true);} });
	else
		jwplayer(id).seek(secs).play(true);
	
	return true;
}

















if (window.$) {
	$(document).ready(function() {
		$("#caption-search-form").submit(function() {
			$("#caption-search .search-start").attr('value', 1);  // Always start at record 1
			process_caption_search(this);
		});  // submit function
	
	
		search_stop();
	
		$("#caption-search .search-prev").submit(function() {
			var prev = $("#caption-search-form").data('prev');
			if (prev) {
				$("#caption-search .search-start").attr('value', prev);
				process_caption_search($("#caption-search-form")[0]);
				//$("#caption-search-form").submit();  // Can't do this because we're resetting the start there
			}
		});  // submit function

		$("#caption-search .search-next").submit(function() {
			var next = $("#caption-search-form").data('next');
			if (next) {
				$("#caption-search .search-start").attr('value', next);
				process_caption_search($("#caption-search-form")[0]);
				//$("#caption-search-form").submit();  // Can't do this because we're resetting the start there
			}
		});  // submit function

	});  // ready function
}





function process_caption_search(thisObject) {
	var savedThis = thisObject;  // Saved for result callbacks to use
	var showPrev = true;
	var showNext = true;
	
	// Stop if we have no search string
	if ("undefined" != typeof(thisObject['q']) && '' == thisObject['q'].value)
		return false;
		
		
	search_start();

	$.ajax({
		url: "/bin/search-caption.php",
		type: "post",
		data: $(thisObject).serialize(),
		dataType: "html",
		timeout: 10000,
		
		success: function(data, textStatus) {
			//console.log("success");
			// Get counts and convert to integers
			var counts = data.match(/ results: (\d+) to (\d+) of (\d+) by (\d+) /);
			if (counts.length >=4) {
				resultsFrom = parseInt(counts[1]);
				resultsTo   = parseInt(counts[2]);
				resultsOf   = parseInt(counts[3]);
				resultsBy   = parseInt(counts[4]);
			} else
				resultsFrom = resultsTo = ResultsOf = ResultsBy = 0;
				
			//console.log(counts[1] +" to " + counts[2] + " of " + counts[3] + " by " + counts[4]);
			
			showPrev = (resultsFrom > 1);
			showNext = (resultsTo < resultsOf);
			//console.log("prev=", showPrev, "next=", showNext);

			// Set next/previous amounts & enable/disable as needed
			if (showPrev)
				$("#caption-search-form").data('prev', Math.max(1, resultsFrom - resultsBy));
			else
				$("#caption-search-form").data('prev', 1);
				
			if (showNext)
				$("#caption-search-form").data('next', resultsTo + 1);
			else
				$("#caption-search-form").data('next', resultsOf);

			
			// Show navigation block, if we aren't seeing all data
			if (showPrev || showNext)
				$("#caption-search .search-nav").show();
			else
				$("#caption-search .search-nav").hide();
			
			// Show the results
			if (resultsOf > 0)
				$("#caption-search .search-results-info").html("<p>" + resultsFrom + "-" + resultsTo + " of " + resultsOf + " results:</p>");
			else
				$("#caption-search .search-results-info").html("<p>No matches found.</p>");
			$("#caption-search .search-results").html(data).slideDown();

		},
		
		error: function() {
			$("#caption-search .search-nav").hide();
			$("#caption-search .search-results").html("<p><i><small>Error:  Try again later.<"+"/small><" + "/i><"+"/p>").show('normal');
			$("#caption-search .search-results-info").html("");
		},
		
		complete: function(html, textStatus) {
			search_stop();
			if (showPrev)
				$("#caption-search .search-prev input").removeAttr('disabled');
			else
				$("#caption-search .search-prev input").attr('disabled', 'disabled');
				
			if (showNext)
				$("#caption-search .search-next input").removeAttr('disabled');
			else
				$("#caption-search .search-next input").attr('disabled', 'disabled');
			
				
		}

	});  // ajax
	
	return false;
		
}		



function search_start() {
	$("#caption-search .ajax-throb").show();  // show throbber graphic
	$("#caption-search input[type=submit]").attr('disabled', 'disabled');  // disable submit button
	$("#caption-search .search-results").slideUp().empty();
}


function search_stop() {
	$("#caption-search .ajax-throb").hide();  // hide throbber graphic
	$("#caption-search input[type=submit]").removeAttr('disabled');  // enable submit button
}

