// This is a Greasemonkey user script.
//
// To install, you need Greasemonkey: http://greasemonkey.mozdev.org/
// Then restart Firefox and revisit this script.
// Under Tools, there will be a new menu item to "Install User Script".
// Accept the default configuration and install.
//
//
// --------------------------------------------------------------------
//
// ==UserScript==
// @name          Vox Embed Code
// @namespace     http://www.vox.com/
// @description   Get Embed code for Vox assets
// @include       http://*.vox.com/library/book*
// @include       http://*.vox.com/library/audio*
// @include       http://*.vox.com/library/photo*
// @include       http://*.vox.com/library/video*
// ==/UserScript==

// This builds the little text area with the embed code in it
unsafeWindow.showEmbedCode = function() {
	fullCode = asset;
	fullCode += "<BR>";
	fullCode += "<a href=\""+assetURL+"\">"+assetTitle+"</a> - posted at <a href=\""+assetHost+"\">"+assetHost+"</a>";

	embedDiv.innerHTML = "Use this code to embed this on your blog:<BR>";
	embedDiv.innerHTML +=	"<textarea cols=\"20\" rows=\"10\">"+fullCode+"</textarea>";
}

// Use the same code that's used to render the item in the asset detail page
asset = getElementsByClass("asset-image-inner")[0].innerHTML.replace(/\n/g, "");

// And sneak the rest of the stuff from the other places where it appears
assetTitle = getElementsByClass("asset-name page-header1")[0].innerHTML;
assetOwner = getElementsByClass("about-me-name")[0].innerHTML;
assetURL = window.location.href;
assetHost = "http://" + window.location.host;

// Add a div for embed
embedDiv = document.createElement("div");
shareItem = getElementsByClass("asset-actions-share item")[0];
shareItem.parentNode.insertBefore(embedDiv, shareItem.nextSibling);
embedDiv.innerHTML = "<a href=\"javascript:showEmbedCode();\">Embed</a>";

// Helper function to find elements by class name
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}