var firstAmazonSearchShow = true;
var previousAmazonSearch =
{
	keywords: null,
	type: null
};

window.addEvent('domready', function()
{
	var button = $("amazon_search_button")
	var container = $("amazon_search_window");
	if (container)
	{
		container.fade('hide');
		container.setStyles({
			top: button.getPosition().y + button.getSize().y,
			left: button.getPosition().x
		});
	}
});

function DelayAddAmazonInfo()
{
	window.setTimeout(AddAmazonInfo, 500);
}

function AddAmazonInfo()
{
	var openDetail;
	var pitch = 130; // minimum vertical pitch between outputs
	var itemoffset = 0; // vertical offset of image top from ref link
	var left = $('rightcolumn').getCoordinates().left;
	var re = /(?:\/dp\/)\w+/i; // gets the asin from a href
	var top = -1; // tracks output top coordinates
	var amazonPosts = new Array(); // contains the data for all the item infos to be fetched
	// loop over each post
	$$('div[id^=fb_message_]').each(function (post)
	{
		var amazonPost =
		{
			post  : post,
			infos : new Array()
		};
		// loop over links in post
		amazonPost.post.getElements('div.fb_text a[href]').each(function (link)
		{
			var href = link.get('href');
			if (href && href.toLowerCase().indexOf('amazon') > -1)
			{
				var asins = re.exec(href);
				if (asins && asins.length > 0)
				{
					// we found an amazon link in post
					var asin = asins[0].substr(4); // strip '/dp/' from string
					// see if this asin is already linked in this post (should be rare)
					var add = true;
					amazonPost.infos.each(function (info)
					{
						add = add && info.asin != asin;
						// TODO: if the asin is already in some other post on this page, you only want to fetch it once, but show it next to each post in which it appears
						// TODO: add a hover link to the anchor tag to show the same info & also flash the matching image
					});
					if (add)
					{
						// this asin is not already in post, so add it
						amazonPost.infos[amazonPost.infos.length] =
						{
							asin : asin,
							top  : link.getTop() + itemoffset
						}
					}
				}
			}
		}); // amazonPost.post.getElements('div.fb_text a[href]').each(function (link)
		if (amazonPost.infos.length > 0)
		{
			amazonPosts[amazonPosts.length] = amazonPost;
		}
	}); // $$('div[id^=fb_message_]').each(function (post)
	amazonPosts.each(function (amazonPost)
	{
		amazonPost.infos.each(function (info)
		{
			if (info.top < top + pitch)
			{
				info.top = top + pitch;
			}
			top = info.top;
		});
	});
	amazonPosts.reverse().each(function (amazonPost)
	{
		amazonPost.infos.reverse().each(function (info)
		{
			// make image wrapper & get image into it
			var itemWrapper = MakeItemInfoWrapper(info.top, info.asin);
			itemWrapper.inject(amazonPost.post);
			var parameters = "size=120&asin=" + info.asin;
			new Request(
			{
				method     : "get",
				link       : "chain",
				url        : "/search/getitemimage.php",
				onComplete : function (response)
				{
					new Element("span")
						.set("html", response)
						.getElement("img")
						.inject(itemWrapper)
						.addEvent("click", function()
						{
							OnClickAmazonInfo(itemWrapper);
						});
					setTimeout(function ()
						{
							new Request(
							{
								method     : "get",
								link       : "chain",
								url        : "/search/getamazoniteminfo.php",
								onComplete : function (response2)
								{
									var details = new Element("span");
									details.set("html", response2);
									var content = details.getElement("div");
									content.setStyles(
										{
											"z-index"  : 1,
											"width"    : 0,
											"height"   : 0,
											"position" : "absolute",
											"left"     : left - 15,
											"top"      : info.top - 30
										});
									content.fade('hide');
									content.injectBefore(itemWrapper);
									// compat moo 1.1
									var tabber = content.getElement("div.tabber");
									new tabberObj(
									{
										'div' : tabber
									});
									// compat moo 1.2
									//.tabber = new tabberObj(null);
									$('fb_amazon_item_info_details_close_' + info.asin).addEvent("click", function()
									{
										OnClickAmazonInfo(itemWrapper);
									});
								}
							}).send(parameters2);
						}, 500); // setTimeout(function ()
				} // onComplete : function (response)
			}).send(parameters);
			// make item details wrapper and get data into it
			var parameters2 = "asin=" + info.asin;
		}); // amazonPost.infos.each(function (info)
	}); // amazonPosts.each(function (amazonPost)
	//
	// HELPER METHODS
	//
	function MakeItemInfoWrapper (top, asin, zindex)
	{
		var itemWrapper = new Element('div',
		{
			id     : 'bb_item_info_' + asin,
			'class': 'bb_item_info',
			styles :
			{
				'left'       : left + 5,
				'top'        : top,
				'z-index'    : zindex
			}
		});
		return itemWrapper;
	}

	function OnClickAmazonInfo(itemWrapper)
	{
		var details = itemWrapper.getPrevious();
		if (details._sliderOpen == null)
		{
			details._sliderOpen = false;
		}
		if (details._sliderOpen)
		{
			new Fx.Morph(details)
				.start(
					{
						"left"   : itemWrapper.getLeft() - 20,
						"width"  : 0,
						"height" : 0
					})
				.chain(function ()
					{
						details.setStyle("opacity", 0);
					}
				)
				.chain(function ()
					{
						itemWrapper.setStyle("z-index", 0);
						openDetail = null;
					});
		}
		else
		{
			if (openDetail != null)
			{
				openDetail.setStyle("opacity", 0)
					.getNext()
					.setStyle("z-index", 0);
			}
			itemWrapper.setStyle("z-index", 2);
			details
				.setStyle("opacity", 1)
				.morph(
				{
					"left"   : itemWrapper.getLeft() - 550,
					"width"  : 530,
					"height" : 500
				});
			openDetail = details;
		}
		details._sliderOpen = details._sliderOpen == false;
	} // function OnClickAmazonInfo(img)

} // function AddAmazonInfo()

function initAmazonSearch(type)
{
	var keywords = getKeywords();
	showContainer();
	execAmazonSearch(type, keywords);
}

function execAmazonSearch(type, keywords)
{
	if (type)
	{
		setSearchType(type);
	}
	else
	{
		type = getSearchType();
	}
	if (!keywords)
	{
		var textbox = $("amazon_search_keywords");
		keywords = textbox.value;
	}
	if (keywords
		&& (keywords != previousAmazonSearch.keywords
			|| type != previousAmazonSearch.type))
	{
		$("amazon_search_results_container_result").setStyles({display: "none"});
		$("amazon_search_results_container_searching").setStyles({display: "block"});
		$("amazon_search_keywords").value = keywords;
		previousAmazonSearch.keywords = keywords;
		previousAmazonSearch.type = type;
		var parameters = "keywords=" + keywords
			+ "&type=" + type;
		submitting = true;
		new Request(
			{
				method: 'get',
				link: "cancel",
				url: "/search/searchamazon.php",
				onComplete: function (response)
					{
						submitting = false;
						$("amazon_search_results_container_searching").setStyles({display: "none"});
						$("amazon_search_results_container_result").setStyles({display: "block"});
						var results = $("amazon_search_results_container_result");
						if(response.indexOf("<tr ") > -1)
						{
							results.innerHTML = response;
						}
						else
						{
							results.innerHTML = "No matching items.";
						}
					}
			}).send(parameters);
	}
	else
	{
		$("amazon_search_results_container_searching").setStyles({display: "none"});
		$("amazon_search_results_container_result").setStyles({display: "block"});
	}
}

function getKeywords ()
{
	var keywords = getTextareaSelection();
	if (!keywords)
	{
		keywords = previousAmazonSearch.keywords;
	}
	return keywords;
}

function showContainer()
{
	var container = $("amazon_search_window");
	container.fade('in');
}

function setSearchType(type)
{
	var options = $$('#amazon_search_options input');
	options.each(function (option, i)
	{
		if (option.value == type)
		{
			option.checked = true;
		}
	});
}

function getSearchType ()
{
	var value = null;
	var options = $$('#amazon_search_options input');
	options.each(function (option, i)
	{
		if (option.checked)
		{
			value = option.value;
		}
	});
	return value;
}

function MakeAmazonLink(asin, title)
{
	$('amazon_search_window').fade('hide');
	var caption = getTextareaSelection();
	if (!caption)
	{
		caption = title;
	}
	var text = "[url=http://www.amazon.com/dp/" + asin + "/]" + caption + "[/url]";
	PostWrite(text);
}

function DoReply(id)
{
	var quote = getTextareaSelection();
	if (!quote && id)
	{
		var message = $('fb_message_' + id);
		if (message)
		{
			quote = $(message).getElement('.fb_text');
			quote = quote.innerText || quote.textContent || '';
			quote = quote.trim();
		}
	}
	PostWrite("[quote]" + quote + "[/quote]\n\n");
}

/*
 * AUTOGROW TEXTAREA
 * Version 1.0
 * A mooTools plugin
 * by Gary Glass (www.bookballoon.com)
 * mailto:bookballoon -at- bookballoon.com
 *
 * Based on a jQuery plugin by Chrys Bader (www.chrysbader.com).
 * Thanks to Aaron Newton for reviews and improvements.
 *
 * Copyright (c) 2009 Gary Glass (www.bookballoon.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * NOTE: This script requires mooTools. Download mooTools at mootools.net.
 *
 * USAGE:
 *		new AutoGrow(element);
 * where 'element' is a textarea element. For example:
 *		new AutoGrow($('myTextarea'));
 */
var AutoGrow = new Class({

	Implements: [Options, Events],

	options: {
		interval: 333, // update interval in milliseconds
		margin: 30, // gap (in px) to maintain between last line of text and bottom of textarea
		minHeight: 0 // minimum height of textarea
	},

	initialize: function(textarea, options) {
		this.textarea = $(textarea);
		this.options.minHeight = textarea.clientHeight;
		this.setOptions(options);
		this.dummy =  new Element("div", {
			styles:	{
				"overflow-x" : "hidden",
				"position"   : "absolute",
				"top"        : 0,
				"left"       : "-9999px"
			}
		}).setStyles(this.textarea.getStyles("font-size", "font-family", "width", "line-height", "padding"))
			.inject(document.body);
		this.resize.periodical(this.options.interval, this);
	},

	resize: function() {
		var html = this.textarea.get('value').replace(/\n|\r\n/g, '<br>X');
		if (this.dummy.get("html").toLowerCase() != html.toLowerCase()){
			this.dummy.set("html", html);
			var triggerHeight = this.dummy.getSize().y + this.options.margin;
			if (this.textarea.clientHeight != triggerHeight)
			{
				var newHeight = Math.max(this.options.minHeight, triggerHeight);
				this.textarea.tween("height", newHeight);
			}
		}
	}

});

