function to_timeago(elem, ts) {
	var d = new Date(parseInt(ts) * 1000);
	elem.data("timeago", { datetime: d });
	elem.timeago();
}

function gravatar_url(md5, s) {
	s = s || 32;
	return "http://gravatar.com/avatar/" + md5 + "?s=" + s;
}

function search_url(q) {
	return "/home/search_friend/" + q;
}

function accept_friend_request_url(uid, fid) {
	var u = ["/home/accept_friend_request", uid, fid];
	return u.join("/");
}

function decline_friend_request_url(uid, fid) {
	var u = ["/home/decline_friend_request", uid, fid];
	return u.join("/");
}

function solicit_friend_request_url(uid, fid) {
	var u = ["/home/send_friend_request", uid, fid];
	return u.join("/");
}

function trace_url(iid, from, to) {
	var u = ["/home/trace", iid, from, to];
	return u.join("/");
}

function explore_url(iid, start) {
	start = start || -1;
	var u = ["/home/explore", iid, start];
	return u.join("/");
}

function latest_url(uid, limit) {
	limit = limit || 30;
	var u = ["/home/latest", uid, limit ];
	return u.join("/");
}

function new_idea_url(uid) {
	var u = ["/home/share_new_idea", uid];
	return u.join("/");
}

function recycle_idea_url(iid, uid) {
	var u = ["/home/reshare_idea", iid, uid];
	return u.join("/");
}

function friend_requests_url(uid) {
	return "/home/get_friend_requests/" + uid;
}

function fb_link_idea_url(uid) {
	return "/home/fb_symlink_idea/" + uid;
}

function tw_post_and_link_idea_url(uid) {
	return "/home/tw_tweet_and_symlink/" + uid;
}

function idea_glorified_url(iid, uid) {
	var u = ["http://traceitfor.me/home/an_idea_can_change_your_life", iid, uid];
	return u.join("/");
}

function settings_url(uid) {
	return "/home/settings/" + uid;
}

function save_settings_url(uid) {
	return "/home/save_settings/" + uid;
}

function alert_or_function(s, f) {
	if (f) {
		return f;
	}
	else {
		return function() {
			alert(s);
		};
	}
}


/* Fetches the twitter friendly text for an idea. It basically does 3 things:
 * 1. Shortens the complete text to < 141 characters
 * 2. Adds a bit.ly URL at the end of the text to the idea on traceitfor.me
 * 3. If the complete idea text doesn't fit in the space given, appends 3 dots
 *    to the end of the idea text (but before the bit.ly link).
 *
 *
 * Arguments:
 *
 * idea => The idea object
 *
 * contact => The contact to which this idea is to be directed
 * 			  (if it is a single recipient idea or a single
 * 			  recipient reply). Otherwise, pass null.
 *
 * cb => The callback to call with the new idea text.
 *
 */
function tw_idea_text(idea, contact, cb) {
	idea.text = jQuery.trim(idea.text);
	if (contact && contact.tw_username && idea.text.search("@" + contact.tw_username) == -1) {
		idea.text = "@" + contact.tw_username + ": " + idea.text;
	}

	var url = idea_glorified_url(idea.iid, contact ? contact.uid : -1);

	$.bitly.shorten({
		url: url,
		callback: function(r) {
			if (r.status_code == 200) {
				/* Success */
				var ulen = r.data.url.length;
				if (idea.text.length + ulen + 1 > 140) {
					idea.text = idea.text.substring(0, 140-4-ulen) + "... " + r.data.url;
				}
				else {
					idea.text = idea.text + " " + r.data.url;
				}
			}
			else {
				/* Failure */
			}

			/* Callback in either case */
			cb(idea, contact);
		}
	});
}

function get_keys(o) {
	var r = [ ];
	for (var i in o) r.push(i);
	return r;
}

function htmlentities(s) {
	return s.replace(/&/g,"&amp;")
		.replace(/</g,"&lt;")
		.replace(/>/g,"&gt;")
		.replace(/"/g,"&quot;")
		.replace(/'/g,"&apos;");
}

function profile_image_url(ud) {
	if (ud.fbid) {
		return "https://graph.facebook.com/" + ud.fbid + "/picture";
	}
	return gravatar_url(ud.email_md5);
}

function significant_whitespaces(s) {
	return s.replace(/\n/g, "<br/>");
}

function insignificant_whitespaces(s) {
	return s.replace(/[\s]+/g, ' ');
}

function pluralize(s, count, suffix) {
	suffix = suffix || "s";
	if (count == 1) {
		return s;
	}
	return s + suffix;
}

function shorten_sentence(s, len) {
	// console.log("shorten_sentence(", s, len, ")");
	len = len || 1;

	s = jQuery.trim(s);

	if (s.length <= len) {
		return s;
	}

	/* Start from index len-1 till we find a space. We'll assume that
	 * this works. We don't care about 100% correctness here.
	 */
	while (len > 0 && s[len-1].search(/[\s]/) == -1) {
		len -= 1;
	}
	/* Return the portion of the text before len with 3 dots
	 * appended to it.
	 *
	 */
	var p = jQuery.trim(s.substring(0, len));
	var ctr = 3;

	/* Handle the case when the original string ends in ...
	 * (I'm basically doing this because I have this dirty habit :-p)
	 *
	 */
	while (p.length > 0 && ctr > 0 && p[p.length-1] == ".") {
		p = p.substring(0, p.length-1);
	}
	return p + " ...";
}


function decimal_to_binary(n) {
	return Number(n).toString(2);
}

/* Use as $(selector).selectRange(0,0), etc...
 * Use only on textarea elements
 *
 * Picked up from this thread on SO:
 * http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area
 *
 */
$().ready(function() {
	$.fn.selectRange = function(pos) {
		this.each(function(index, elem) {
			if (elem.setSelectionRange) {
				elem.setSelectionRange(pos, pos);
			} else if (elem.createTextRange) {
				var range = elem.createTextRange();
				range.collapse(true);
				range.moveEnd('character', pos);
				range.moveStart('character', pos);
				range.select();
			}
		});
		return this;
	};
});



/* Hack */
if (!window.console_) {
	window.console_ = {
		log: function() {
			if (window.console) {
				window.console.log.apply(window.console, arguments);
			}
		},
		warn: function() {
			if (window.console) {
				window.console.warn.apply(window.console, arguments);
			}
		},
		error: function() {
			if (window.console) {
				window.console.error.apply(window.console, arguments);
			}
		}
	};
}

