/* ASSUMES PROTOTYPE.JS IS LOADED
 *
 * Quoted media (images and youtube videos) replacer by johnwoo.
 * Replaces quoted images with a thumbnail with preview-tooltip on hover.
 * Replaces youtube videos with embedded players (or adds titles to quoted videos).
 * Usage: load prototype.js, then load this file at the end of an IPB topic page.
 *
 * 21-MAY-2008 Initial version.
 * 22-MAY-2008 Moved tooltip show/hide code into their own methods; added fade in/out code.
 * 17-JUN-2011 All new YouTube video code. BB-code generates thumbnails instead of embedded
 *             players; this script creates the players from the thumbnails and adds titles
 *             to quoted video thumbnails. Also added CSS3 drop shadow to image thumbnail
 *             tooltips (only on CSS3-compatible browsers).
 */

var QUOTED_IMAGE_PROCESSOR = {
	
	QUOTED_IMAGE_HEIGHT: 40,
	QUOTED_IMAGE_TOOLTIP_SIZE: 300,
	
	process: function(img) {
		if (img.height > QUOTED_IMAGE_PROCESSOR.QUOTED_IMAGE_HEIGHT) {
			// This image is too high - replace it with a link.
			var a = document.createElement('a');
			a.href = img.src;
			img.title = 'Origineel: ' + img.width + ' x ' + img.height + ' pixels';

			var factor = img.height / QUOTED_IMAGE_PROCESSOR.QUOTED_IMAGE_HEIGHT;
			img.style.width = Math.round(img.width / factor) + 'px';
			img.style.height = QUOTED_IMAGE_PROCESSOR.QUOTED_IMAGE_HEIGHT + 'px';
			img.alt = img.src;

			img.parentNode.replaceChild(a, img);
			a.appendChild(img);

			a.onmouseover = function() {
				img.showTooltip();
			};
			a.onmouseout = function() {
				img.hideTooltip();
			};
			a.onclick = function() {
				// Remove tooltip when image clicked to prevent it from showing
				// after using the browser's Back button to return to this page.
				img.hideTooltip(true);
			};
		}
	},
	
	showTooltip: function(img) {
		if (!img.tooltip) {
			var body = $(document.body),
				pos = img.cumulativeOffset();
			
			img.tooltip = new Element("img", {src: img.src}).setStyle({
				position: "absolute",
				padding: "2px",
				backgroundColor: "#fff",
				border: "1px solid #8394b2"
			});
			var tooltipSize = {
				width: img.tooltip.width,
				height: img.tooltip.height
			};
			if (tooltipSize.width > QUOTED_IMAGE_PROCESSOR.QUOTED_IMAGE_TOOLTIP_SIZE || tooltipSize.height > QUOTED_IMAGE_PROCESSOR.QUOTED_IMAGE_TOOLTIP_SIZE) {
				if (tooltipSize.width >= tooltipSize.height) {
					tooltipSize.height = Math.round(tooltipSize.height * (QUOTED_IMAGE_PROCESSOR.QUOTED_IMAGE_TOOLTIP_SIZE / tooltipSize.width));
					tooltipSize.width = QUOTED_IMAGE_PROCESSOR.QUOTED_IMAGE_TOOLTIP_SIZE;
				} else {
					tooltipSize.width = Math.round(tooltipSize.width * (QUOTED_IMAGE_PROCESSOR.QUOTED_IMAGE_TOOLTIP_SIZE / tooltipSize.height));
					tooltipSize.height = QUOTED_IMAGE_PROCESSOR.QUOTED_IMAGE_TOOLTIP_SIZE;
				}
				img.tooltip.setStyle({
					width: tooltipSize.width + "px",
					height: tooltipSize.height + "px"
				});
			}
			// Modern browsers get a subtle CSS3 drop shadow.
			img.tooltip.setStyle("-webkit-box-shadow: 0px 1px 3px 0px #444;");
			img.tooltip.setStyle("-moz-box-shadow: 0px 1px 3px 0px #444;");
			img.tooltip.setStyle("box-shadow: 0px 1px 3px 0px #444;");

			pos.top += 2;
			img.tooltip.setStyle({
				left: pos.left + "px",
				top: (pos.top + QUOTED_IMAGE_PROCESSOR.QUOTED_IMAGE_HEIGHT + 12) + "px",
				opacity: 0.1
			});
			img.tooltip.arrow = new Element("img", {src: "jscripts/quote_tag_arrow.png"}).setStyle({
				position: "absolute",
				left: (pos.left + parseInt(img.offsetWidth / 2) - 6) + "px",
				top: (pos.top + QUOTED_IMAGE_PROCESSOR.QUOTED_IMAGE_HEIGHT) + "px",
				opacity: 0.1
			});
			body.insert(img.tooltip).insert(img.tooltip.arrow);
			
			var opacity = 0.0;
			new PeriodicalExecuter(function(pe) {
				if (img.tooltip && opacity < 1.0) {
					opacity += 0.2;
					img.tooltip.setOpacity(opacity);
					img.tooltip.arrow.setOpacity(opacity);
				} else {
					pe.stop();
				}
			}, 0.03);
		}
	},
	
	hideTooltip: function(img, no_fade) {
		if (img.tooltip) {
			if (no_fade) {
				document.body.removeChild(img.tooltip.arrow);
				document.body.removeChild(img.tooltip);
			} else {
				// Save tooltip to a local var and detach it from its image
				// so that a new one may be created when hovered over while
				// this one is fading out.
				var tooltip = img.tooltip;
				var opacity = tooltip.getStyle('opacity');
				new PeriodicalExecuter(function(pe) {
					if (opacity > 0.2) {
						opacity -= 0.2;
						tooltip.setOpacity(opacity);
						tooltip.arrow.setOpacity(opacity);
					} else {
						pe.stop();
						tooltip.arrow.remove();
						tooltip.remove();
					}
				}, 0.03);
			}
			img.tooltip = null;
		}
	}
	
};

(function() {
	var body = $(document.body);
	
	// Apply the quoted image processor's methods to all image elements.
	Element.addMethods('img', QUOTED_IMAGE_PROCESSOR);

	// Find images in quotes. Replacing is done by the quoted image processor.
	body.select('div.quotemain img.linked-image').each(function(img) {
		if (img.hasClassName("linked-image")) {
			if (img.complete) {
				// If the image is loaded already, process it now.
				img.process();
			} else {
				// Otherwise, have it processed as soon as it's loaded.
				img.onload = function() {
					this.process();
				};
			}
			// Prevent the image from being selected for processing
			// more than once (in case of nested quotes).
			img.removeClassName('linked-image');
		}
	});

	// Keep track of the ID's of quoted videos.
	var quoted_video_ids = new Array();

	// Replace youtube thumbnails with embedded players, but not inside quotes.
	body.select("img.youtube").each(function(thumb) {
		// Get the video ID.
		var video_id = false;
		$w(thumb.className).each(function(className) {
			if (className.startsWith("youtube_")) {
				video_id = className.substr(8);
				throw $break;
			}
		});

		// If we did not find a video ID for this thumbnail, continue with the next thumbnail.
		if (!video_id) return;

		// Check if the video thumbnail is inside a quote.
		if (thumb.up("div.quotemain")) {
			// If it is, save the video ID to the quoted videos list.
			if (!quoted_video_ids.include(video_id)) quoted_video_ids.push(video_id);
		} else {
			// If this thumbnail is not inside a quote, replace it with a player.
			thumb.up().replace('<object height="350" width="425"><param name="movie" value="http://www.youtube.com/v/' + video_id + '"><param name="wmode" value="transparent" /><embed src="http://www.youtube.com/v/' + video_id + '" type="application/x-shockwave-flash" wmode="transparent" height="350" width="425" /></object>');
		}
	});
	
	// LEGACY: Embedded players may still exist inside quotes if they were put there before by the old BB-code.
	// Replace these quoted embedded players with thumbnails. The subsequent new code will add video information to the thumbnail.
	body.select("div.quotemain object").each(function(obj) {
		var params = obj.select('param[name="movie"]');
		if (params.length >= 1) {
			var video_id = params[0].value.replace("http://www.youtube.com/v/", "");
			
			if (video_id && video_id != "") {
				var a = new Element("a", {href: "http://youtube.com/watch?v=" + video_id});

				a.insert(new Element("img", {src: "http://img.youtube.com/vi/" + video_id + "/2.jpg", "class": "youtube youtube_" + video_id}));
				obj.replace(a);
				// Save the video ID to the quoted videos list.
				if (!quoted_video_ids.include(video_id)) quoted_video_ids.push(video_id);
			}
		}
	});
	// END LEGACY

	// Add video information to thumbnails inside quotes.
	if (quoted_video_ids.size() > 0) {
		// If there are quoted video thumbnails, get their video titles.
		new Ajax.Request("/youtube_video_info.json.php", {
			parameters: {
				video_ids: quoted_video_ids.join(",")
			},
			onSuccess: function(transport) {
				var result = (transport.responseText || '{error:"No response from server."}').evalJSON();

				if (result.error) {
					body.insert('<p style="font-size: 7pt;">YouTube video info error: ' + result.error.escapeHTML() + '</p>');
				} else if (result.videos) {
					result.videos.each(function(video) {
						var minutes = parseInt(video.length_seconds / 60),
							seconds = video.length_seconds % 60;

						body.select("img.youtube_" + video.id).each(function(thumb) {
							var div = new Element("div").setStyle({display: "inline-block", position: "relative"}),
								videoTitle = new Element("span").setStyle({fontSize: "7pt", color: "#fff", padding: "1px", lineHeight: "1.1em", position: "absolute", zIndex: 999, left: 0, top: 0, right: 0, maxHeight: "2.2em", overflow: "hidden"/*, whiteSpace: "nowrap"*//* to limit the title to 1 line */}),
								videoLength = new Element("span").setStyle({fontSize: "7pt", color: "#fff", padding: "0 1px 1px 0", lineHeight: "1em", position: "absolute", zIndex: 999, left: 0, bottom: 0, right: 0, maxHeight: "1em", textAlign: "right", overflow: "hidden", whiteSpace: "nowrap"}).update(minutes + ":" + (seconds < 10 ? "0" : "") + seconds);

							thumb.title = videoTitle.title = videoLength.title = "YouTube: " + video.title.escapeHTML();
							videoTitle.update(video.title.escapeHTML());
							videoTitle.insert(new Element("div").setStyle({position: "absolute", zIndex: -1, left: 0, top: 0, right: 0, bottom: 0, backgroundColor: "#000", opacity: 0.5}));
							thumb.replace(div);
							div.insert(thumb).insert(videoTitle).insert(videoLength);
						});
					});
				}
			}
		});
	}
})();

