// Global var to keep track of the search timeout
var searchTimeout = undefined;

function searchTags(callback) {
	if (undefined == callback) {
		// Set a timer to do the search after 250ms of no typing.
		if (undefined != searchTimeout)
			clearTimeout(searchTimeout);
		searchTimeout = setTimeout('searchTags(true)', 250);
	} else {
		// Just search the last tag they typed.
		var searchName = $('#tags').val();
		searchName = searchName.split(',');
		searchName = trim(searchName[searchName.length - 1]);

		// Fire off a tag search, returning JSON
		$.getJSON('/admin/tags/fetch', {'name': searchName}, function(tags){
			var html = '',
				tagName = '';
			for (tag in tags) {
				tagName = tags[tag].name;
				html += '<a href="javascript:addTag(\'' + tagName
						+ '\');">' + tagName + '</a><br />\n';
			};
			if ('' == html)
				html = 'No Tags Found';
			$('#tag-selector').html(html).slideDown('slow');
		});
	}
};

function addTag(tagName) {
	var tags = $('#tags').val();
	tags = tags.split(',');
	for (tag in tags)
		if (tag > 0)
			tags[tag] = ' ' + trim(tags[tag]); // Ensure there's only 1 leading space.
	var prefix = '';
	if (tags.length > 1)
		prefix = ' ';
	tags.pop(); // Remove the part-tag we searched for.
	tags.push(prefix + tagName); // Add on the one they selected.
	tags = tags.toString(); // Convert back to a string
	$('#tags').val(tags).get(0).focus();
}

function hideSelector(callback) {
	if (undefined == callback) {
		// I'm using a timer here because if you don't,
		// then the selector disappears before the click
		// can fire on the selector.
		setTimeout('hideSelector(true)', 250);
	} else {
		$('#tag-selector').slideUp('slow');
	};
}

/**
 * Why the hell doesn't javascript have a trim function?!
 *
 * Javascript trim, ltrim, rtrim
 * http://www.webtoolkit.info/
 */
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
