/* Fix non-existing console in IE */
if (typeof console == "undefined") {
    this.console = {log: function() {}};
}

/**
 * Apply encodeURI to all values of the fragment of a URL (hash).
 * @param hash
 *      the hash
 * @return encoded hash
 */
function encodeHash(hash) {
    var params = hash.split('&');
    var result = '';
    $.each(params, function(i, val) {
        var keyval = val.split('=');
        params[i] = keyval[0] + '=' + encodeURIComponent(keyval[1]);
    });
    return params.join('&');
}

/**
 * Render the result of calling auto complete
 * @param ul
 *		 ul containing the result
 * @param item
 *		 result item
 * @param synTextMax
 *		 maximum length of synonyms
 */
function renderAcResult(ul, item, synTextMax) {
	renderItemLi(ul, item, synTextMax, '');
	$.each(item.subs, function(i, val) {
		renderItemLi(ul, val, synTextMax, 'subclass');
	});
	return ul;
}

/**
 * Render the li tag for a given entry without rendering sub concepts.
 * @param ul
 *		 ul containing the result
 * @param item
 *		 result item
 * @param synTextMax
 *		 maximum length of synonyms
 */
function renderItemLi(ul, item, synTextMax, cssClass) {
	line = "<a>" + item.label;
	if (item.syns.length > 0)
		line += ' <span class="synonym">(' + abbreviate(item.syns.join(", "), synTextMax) + ")</span>";
	line += "</a>";
	$("<li class=\""+cssClass+"\"></li>").data("item.autocomplete", item.label).append(line).appendTo(ul);
}

/**
 * Abbreviate a text if it has too many chars. If length is 0 then the text is not abbreviated.
 *
 * @param text
 *		 a text
 * @param length
 *		 number of characters allowed
 * @return the (abbreviated) string
 */
function abbreviate(text, length) {
	if (length > 0 && text.length > length)
		text = text.substr(0, length) + '...'
	return text
}

