$(document).ready(function() {

    // link content in the form of 00.0000 to curia vista geschäftsanzeige
    // index:    [1]            [3]      [4]       [5]
	if ($(".ms-formfieldcontainer").length < 1) {
		var regex = /(\s|&nbsp;|\()((\d{2})\.(\d{3,4}))(\s|&nbsp;|\)|\.|,)/;
		
		$(".content_sp_linklist").each(function() {
			var $this = $(this);
			var m, href, topicid, temp;
			var result = "";

			// bug #357: check whether topicid is inside an existing anchor tag.
			// updated solution: remove all anchors, then process content, after
			// that, readd the anchor elements
			var input = $this.html();
			var links = [];
			$this.find("a").each(function(i) {
				var html = $(this).clone().wrap('<div></div>').parent().html();
				input = input.replace(html, '----'+i+'----');
				links[i] = html;
			});
			// add whitespace around html tags, such that the regex matches
			// topic-ids at the beginning of a text block.
			input = input.replace(/>/g, '> ').replace(/</g, ' <')
			
			var buffer = input;
			while ((m = buffer.match(regex)) != null) {
				topicid = ((parseInt(m[3]) > 80) ? "19" : "20") + m[3];
				topicid += ((m[4].length == 4) ? "" : "0") + m[4];
				href = m[1] + '<a href="/'+i18n.lang+'/suche/'+i18n.pageslist+'/geschaefte.aspx?gesch_id=' + topicid + '">'+ m[2] + '</a>' + m[5];
				result += buffer.substring(0, m.index) + href;
				buffer = buffer.substr(m.index + m[0].length);
			}
			if (buffer.length > 0) {
				result += buffer;
			}
			if (result.length > 0 && result != input) {
				// bug #357: re-add anchor tags.
				$(links).each(function(i, text) {
				   result = result.replace('----'+i+'----', text);
				});
				$this.html(result);
			}
		});    
	}
});