var call_back_function = '';
var map = 'default';

function setup (){

	// Hide buildings table
	document.getElementById('buildings').style.display = 'none';

	var qs = new Querystring();

	// Call back mode
	if (qs.get('callback')){
//		alert('in callback mode');
		call_back_function = qs.get('callback');
		// hide chrome
		document.getElementById('global_links').style.display = 'none';
		document.getElementById('footer').style.display = 'none';
	}
	// find all area tags and add a mouse over event
	var areas = getElementsByTagNames('area');
	for (var c=0; c < areas.length; c++){
		areas[c].onclick = highlight_building;
	}



	// If there is a hash link then show that building to start with
	if (location.hash != ''){
//		alert('hash ' +location.hash);
		var area = findHashLink(location.hash);
		highlight_area_link(area);
	}
	code = qs.get('code');
	map = location.href.replace(/^.*maps\//, '').replace(/\/\?.*$/, '');


	if (code){
//		alert('from query ' + code);
		var area = findHashLink('#'+code);
//		alert(area);

		highlight_area_link(area, sanitize(qs.get('title')), sanitize(qs.get('body')) );
	}
}

/**
 * Given a hash link eg #E23 finds the first <area> tag that links to it
 */
function findHashLink(link){
	var areas = getElementsByTagNames('area');
	var link;
	for (var c=0; c < areas.length; c++){
		hash = areas[c].href.replace(/^.*#/, '#');
		if(hash == link) return areas[c];
	}
}

/**
 * Generic utility function
 * Given a tag name 
 */
function getElementsByTagNames(list,obj) {
	if (!obj) var obj = document;
	var tagNames = list.split(',');
	var resultArray = new Array();
	for (var i=0;i<tagNames.length;i++) {
		var tags = obj.getElementsByTagName(tagNames[i]);
		for (var j=0;j<tags.length;j++) {
			resultArray.push(tags[j]);
		}
	}
	var testNode = resultArray[0];
	if (!testNode) return [];
	if (testNode.sourceIndex) {
		resultArray.sort(function (a,b) {
				return a.sourceIndex - b.sourceIndex;
		});
	}
	else if (testNode.compareDocumentPosition) {
		resultArray.sort(function (a,b) {
				return 3 - (a.compareDocumentPosition(b) & 6);
		});
	}
	return resultArray;
}


/**
 * map_callback
 */
function map_callback(code,name){
	// find the get param
	// call it in window.opener
	// close the window
//	alert('map: '+map);
//	alert('code: '+code);
//	alert('name: '+name);
	var parent_win = window.opener;
	var run = "parent_win."+call_back_function+"('"+map+"','"+code+"','"+name+"')";
	eval(run);
	window.close();

}



/**
 * Displayed a marker on the map
 */
function show_marker(x,y,building_code,title,body){
//	alert('show_marker');
	var mark = document.getElementById('marker');
	if (!mark){
		var marker_holder = document.getElementById('marker_holder');
		marker_holder.innerHTML = '<div id="marker"><div id="marker_close"><a href="#" onclick="return hide_marker();">x</a></div><div id="marker_title"></div><div id="marker_body"></div></div>';
		mark = document.getElementById('marker');
	}




	var mark_body = document.getElementById('marker_body')
	if (body == '&nbsp;'){ body = ''; }
	if (call_back_function){
		mark_body.innerHTML = body + '<p><a href="#" class="portlet-form-button" onclick="return map_callback(\''+building_code+'\',\''+title+'\');"><img src="/images/icons/silk/door_in.gif">Choose this location</a></p>';
	} else { 
		mark_body.innerHTML = body;
	}
	mark.style.display = 'block';
	document.getElementById('marker_title').innerHTML = title + ' (' + building_code + ')';
	mark.style.top = (y - mark.scrollHeight) + 'px';
//	mark.style.left = x + 'px';

	var map_width = document.getElementById('map').width;
	
	if (x > (map_width/2)){
		mark_body.style.backgroundImage = 'url(/maps/bubble_right.gif)';
		mark.style.left = (x-200) + 'px';	
	} else {
		mark_body.style.backgroundImage = 'url(/maps/bubble.gif)';
		mark.style.left = x + 'px';
	}
	//alert('show_marker');

}
/**
 * Takes HTML input and removes everything except for a whitelist of allowed tags and attrbutes
 * Note it does not support nested tags yet?
 */
function sanitize(html){

	// convert all [] tags to <>
	html = html.replace(/\[(.+?)\]/, "<$1>");

	// convert whitelist <> tags to [] with stripped out attributes

	// while list of tags
	var tags = new Array('b', 'li', 'ul', 'ol');

	for(c=0; c<tags.length; c++){
		var tag = tags[c];
		var regex = new RegExp ("<("+tag+")[^>]*?>((.|\n|\r)*?)<\/"+tag+">", "gmi");
		html = html.replace(regex, "[$1]$2[/$1]");
	}

	// allow links ONLY of the strict form <a href="xyz">blah</a>
	var regex = new RegExp ("<a href=\"(.*?)\">(.*?)<\/a>", "gim");
	html = html.replace(regex, "[a href='$1']$2[/a]");


	// remove all <> tags
	html = html.replace(/<(.+?)>/g, '');

	// convert all < and > to html entities
	html = html.replace(/</g, "&lt;");
	html = html.replace(/>/g, "&gt;");

	// replace line breaks
	html = html.replace(/\n/g, '');

	// convert all [] tags to <>
	html = html.replace(/\[(.+?)\]/gm, "<$1>");
	return html;

}




/**
 * Remove the marker
 */
function hide_marker(){
	document.getElementById('marker').style.display = 'none';
	return true;
}


/**
 * Given a ref to an area tag show that building
 */
function highlight_area_link(area, title, body){
//	alert('showing');
	var href = area.href;
	var building_code = href.substr(href.indexOf('#')+1);
	var a_tag;

	// find the center of the building
	var coords = area.coords;
	var coo = coords.split(',');
	var x = 0;
	var y = 0;
	for(i=0; i<coo.length; i+=2){
		x += 1*coo[i];
		y += 1*coo[i+1];
	}
	x = 2 * x / coo.length;
	y = 2 * y / coo.length;

	// show from query or lookup?
	if (title == undefined){
//		alert('load from lookup');
		var a_tag = document.getElementById(building_code);
		if (!a_tag) return;
		var td_tag = a_tag.parentNode.parentNode;
		title = td_tag.getElementsByTagName('td')[1].innerHTML;
		body = td_tag.getElementsByTagName('td')[2].innerHTML;
	}
	show_marker(x,y,building_code,title,body);
}



/**
 * handle the onclick event from the area tags
 */
function highlight_building (e){
    if (!e) var e = window.event;
    var targ;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;

//	alert('onclick'+targ);

	highlight_area_link(targ);
}


window.onload = setup;


/* Client-side access to querystring name=value pairs
	Version 1.2.3
	22 Jun 2005
	Adam Vandenberg
	http://adamv.com/dev/javascript/files/querystring.js
*/
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = new Object()
	this.get=Querystring_get
	
	if (qs == null)
		qs=location.search.substring(1,location.search.length)

	if (qs.length == 0) return

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ')
	var args = qs.split('&') // parse out name/value pairs separated via &
	
// split out each name=value pair
	for (var i=0;i<args.length;i++) {
		var value;
		var pair = args[i].split('=')
		var name = unescape(pair[0])

		if (pair.length == 2)
			value = unescape(pair[1])
		else
			value = name
		
		this.params[name] = value
	}
}

function Querystring_get(key, default_) {
	// This silly looking line changes UNDEFINED to NULL
	if (default_ == null) default_ = null;
	
	var value=this.params[key]
	if (value==null) value=default_;
	
	return value
}

