function getDomain(url) {
   return url.match(/:\/\/(.[^/]+)/)[1];
}
function replacer(str, p1, p2, offset, s) {
	return "<em style='background:#ffff7e;'>[link to a page at <a href='" + str + "' rel='nofollow' target='_blank'>" + getDomain(str) + " <img align='top' src=http://www.google.com/s2/favicons?domain=" + getDomain(str) + " /></a>]</em>";
}
function replacermobile(str, p1, p2, offset, s) {
	return "<em style='background:#ffffcc;'>external link <a href='" + str + "' rel='nofollow'>" + getDomain(str) + " <img align='top' src=http://www.google.com/s2/favicons?domain=" + getDomain(str) + " /></a></em>";
}
jQuery.fn.replaceURLsWithHTMLLinks = function() {
	var html = this.html();
	exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
	var htmlWithLinks = html.replace(exp,replacer);
	this.html( htmlWithLinks);
	return this;
}
jQuery.fn.replaceURLsWithHTMLLinksMobile = function() {
	var html = this.html();
	exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
	var htmlWithLinks = html.replace(exp,replacermobile);
	this.html( htmlWithLinks);
	return this;
}
jQuery.fn.replaceURLsWithHTMLLinksRaw = function() {
	// Remove existing links (to avoid weird nesting when adding later)
	var html = this.html();
	var exp = /<a\s.*href=['"](\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])['"].*>.*<\/a>/ig;
	var htmlMinusLinks = html.replace(exp,"$1");
	// Then add links
	exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
	var htmlWithLinks = htmlMinusLinks.replace(exp,"<a href='$1' rel='nofollow' target='_blank'>$1</a>");
	this.html( htmlWithLinks);
	return this;
}
function swapThumbnail(id,url,size)
{
	if(url === null){ return ""; }
	if(url.indexOf("youtube.com")!=-1)
	{
		//youtube
		size = (size === null) ? "big" : size;
		var vid;
		var results;
		results = url.match("[\\?&]v=([^&#]*)");
		vid = ( results === null ) ? url : results[1];
		if(size == "small"){
			$("#"+id+"").attr({src : "http://img.youtube.com/vi/"+vid+"/2.jpg"});
		}else {
			$("#"+id+"").attr({src : "http://img.youtube.com/vi/"+vid+"/0.jpg"});
		}
	}
	{
		// vimeo
		var vid =  $('<a/>').attr('href',url)[0].pathname.replace(/^[^\/]/,'/').substring(1);
		$.getJSON("http://vimeo.com/api/v2/video/" + vid + ".json?callback=?", function(data) {
			$.each(data, function(index, value) { 
				$("#"+id+"").attr({src : value.thumbnail_small});
			});
		});
	}
}
