/*
 *      Author: Erik Borra - erik@erikborra.net
 *      Copyright (C) 2007, Erik Borra
 *
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or (at
 *      your option) any later version.
 *
 *      This program is distributed in the hope that it will be useful, but
 *      WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *      General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software Foundation,
 *      Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/

// this script makes an interactive google map based on NISEnet data in a mysql database

// define vars
var map; // holds the google map
var logdebug; // if set to true in function reset, some debugging output will be written
var formap; // holds all the data for either persons or either organisations
var roles; // person roles
var addresses; // addresses, should be optimized one day to only get relevant data
var meetings; 
var workgroups; 
var organisations; 
var types; // organisation types
var affiliations; // organisation affiliations
var gmarkers = new Object(); // holds the markers on the map
var visibleElements = new Array(); // holds which elements are currently visible
var allowed_lists = new Array("formap","organisations","meetings","workgroups","types","affiliations","roles"); // define all data vars here, so eval doesn't execute random functions etc
var left_lists = new Array("meetings","workgroups"); // which data is in the bottomleft{header,content}
var activeFilters = new Object(); // which filters are applied to get the current view
var selectedRightView; // keeps track of the current right view
var urlwhat;
var urlview;
var urlworkgroups;
var urlmeetings;
var urltoggle;
var size;

// define google map
function onLoad(what,view,workgroups,meetings,toggle,urlsize) {
	urlview = view;
	urlworkgroups = workgroups;
	urlmeetings = meetings;
	urltoggle = toggle;
	if(urlsize == '') size = 'full';
	else size = urlsize;
   if(GBrowserIsCompatible()) {
		if(size == 'widget') {
			map = new GMap(document.getElementById('smallmap'));
			map.centerAndZoom(new GPoint(-92,35), 15);
		} else {
      	map = new GMap(document.getElementById('map'));
      	map.addControl(new GLargeMapControl());
      	map.addControl(new GMapTypeControl());
      	map.centerAndZoom(new GPoint(-30,35), 15);
		}
      new GKeyboardHandler(map);
      map.enableContinuousZoom();
      map.enableDoubleClickZoom();
		if(what != '') doQuery(what);
		else doQuery('persons');
   }
}

/*************************************************
 parse  and handle the results from the ajax request
*************************************************/

function parseResult(result) {
	var resultString = cleanupResponseString(result);
	var data = eval("(" + resultString + ")");

	// data which is always present
	if(data['addresses'] != undefined && data['meetings'] != undefined && data['workgroups'] != undefined && data['organisations'] != undefined) {
		addresses = data['addresses'];
		meetings = data['meetings'];
		workgroups = data['workgroups'];
		organisations = data['organisations'];
	}

	leftcontent = rightheader = rightcontent = '';
	// data for persons
	if(data['roles'] != undefined && data['persons'] != undefined) {
		hideDisplay('legend_type');
		toggleDisplay('legend_role');
		roles = data['roles'];
		formap = data['persons'];
		for(i in formap) {
			if(formap[i].name != undefined && i != 214) {
				visibleElements.push(i);
				addmarker(i);
			}
		}
		selectedRightView = 'roles';
		if(size != 'widget' && size != undefined) {
			leftcontent += '<ul style="border-bottom: 1px dotted #816F5B;"><li><a href="javascript:removeAllFilters(); javascript:hideDisplay(\'workgroups\'); javascript:toggleMap(\'meetings\',\'\',\'meetings\'); javascript:setBottomRightContent(list(\'default\',\'block\')); javascript:resizeMap();">Meetings</a></li>';
			leftcontent += "<li>" + list('meetings','none') + "</li></ul>"
			leftcontent += '<ul><li><a href="javascript:removeAllFilters(); javascript:hideDisplay(\'meetings\'); javascript:toggleMap(\'workgroups\',\'\',\'workgroups\'); javascript:setBottomRightContent(list(\'default\',\'block\')); javascript:resizeMap();">Workgroups</a></li>';
			leftcontent += "<li>" + list('workgroups','none') + "</li></ul>"
			rightheader += '<a href="javascript:removeRightFilters();javascript:setBottomRightContent(list(\'roles\',\'block\'));">Roles</a> / ';
		//	rightheader += '<a href="javascript:removeRightFilters();javascript:setBottomRightContent(list(\'organisations\',\'block\'));">Organisations</a> / ';
			rightheader += '<a href="javascript:removeRightFilters();javascript:setBottomRightContent(list(\'formap\',\'block\'));">Persons</a></span>';
			rightcontent += list('roles','block');
		}
	} 
	// data for organisations
	if(data['types'] != undefined && data['affiliations'] != undefined) {
		hideDisplay('legend_role');
		toggleDisplay('legend_type');
		types = data['types'];
		affiliations = data['affiliations'];
		formap = data['organisations'];
		for(i in formap) {
			if(formap[i].name != '') {
				visibleElements.push(i);
				addOrganisationMarker(i);
			}
		}
		selectedRightView = 'types';
		if(size != 'widget' && size != undefined) {
			leftcontent += '<ul style="border-bottom: 1px dotted #816F5B;"><li><a href="javascript:removeAllFilters(); javascript:hideDisplay(\'workgroups\'); javascript:toggleMap(\'meetings\',\'\',\'meetings\'); javascript:setBottomRightContent(list(\'default\',\'block\')); javascript:resizeMap()">Meetings</a></li>';
			leftcontent += "<li>" + list('meetings','none') + "</li></ul>"
			leftcontent += '<ul><li><a href="javascript:removeAllFilters(); javascript:hideDisplay(\'meetings\'); javascript:toggleMap(\'workgroups\',\'\',\'workgroups\'); javascript:setBottomRightContent(list(\'default\',\'block\')); javascript:resizeMap();">Workgroups</a></li>';
			leftcontent += "<li>" + list('workgroups','none') + "</li></ul>"
			rightheader += '<a href="javascript:removeRightFilters();javascript:setBottomRightContent(list(\'types\',\'block\'));">Types</a> / ';
			rightheader += '<a href="javascript:removeRightFilters();javascript:setBottomRightContent(list(\'affiliations\',\'block\'));">Affiliations</a> / ';
			rightheader += '<a href="javascript:removeRightFilters();javascript:setBottomRightContent(list(\'formap\',\'block\'));">Organisations</a></span>';
			rightcontent += list('types','block');
		}
	}
	if(size != 'widget' && size != undefined) {
		setBottomLeftContent(leftcontent);
		setBottomRightHeader(rightheader);
		setBottomRightContent(rightcontent);
	}
	if(urlview != '' && urlview != undefined) {
		if(urlworkgroups != undefined && urlworkgroups != '') {
			activeFilters['workgroups'] = urlworkgroups.split(",");
			toggleDisplay('workgroups');
		}
		if(urlmeetings != undefined && urlmeetings != '') {
			activeFilters['meetings'] = urlmeetings.split(",");
			toggleDisplay('meetings');
		}
		filter('','');
		if(size != 'widget' && size != undefined) {
			selectedRightView = urlview;
			setBottomRightContent(list('default','block'));
		} else if(size == 'widget') {
			setSmallMapInfo(list('formap','none'));
		}
		resizeMap();	
		if(urltoggle != undefined && urltoggle != '') {
			var toggles = urltoggle.split(",");
			for(var t in toggles) {
				if(typeof toggles[t] != 'function') toggleMap(urlview,toggles[t],'');
			}
		}
		updateStatus();
		urlview = '';
	}

	debug(timer.since() + ' ms for full run');
}

/*************************************************
 FILTER AND LISTING 
*************************************************/

function filter(what,el) {
	visibleElements = [];
	for(i in gmarkers) { // reset
		if(gmarkers[i].show) gmarkers[i].show();
		visibleElements.push(i);
	}

	if(what != '' && el != '') { // add filter
		if(!activeFilters[what]) activeFilters[what] = new Array();
		activeFilters[what].push(el);
	} else if (what != '') { // enable all possible values for a list
		which_list = eval(what);
		for(el in which_list) {
			if(which_list[el]) {
				if(!activeFilters[what]) activeFilters[what] = new Array();
				activeFilters[what].push(el);
			}
		}
	}
	applyFilters();
}

// apply filters so markers are hidden / shown 
// and that we know the visibleElements for the listing
function applyFilters() {
	for(which_list in activeFilters) {
		if(which_list != 'formap') {
			// debug(which_list);
			var shown = new Array();
			for(which_el in activeFilters[which_list]) {
				if(typeof activeFilters[which_list][which_el] != 'function') {
		//			debug(activeFilters[which_list][which_el]);
					for(i in gmarkers) {
						if(formap[i] [which_list].inArray(activeFilters[which_list][which_el]) && visibleElements.inArray(i)) {
							shown.push(i);
						}
					}
				}
			}
			for(i in gmarkers) {
				if(formap[i]) {
					if(shown.inArray(i)) {
						if(gmarkers[i].show) gmarkers[i].show();
					} else {
						if(gmarkers[i].hide) gmarkers[i].hide();
						visibleElements.remove(i);
					}
				}
			}
		}
	}
}

// remove all filters
function removeAllFilters() {
	activeFilters = new Object;
	visibleElements = new Array;
	for(i in gmarkers) {
		if(gmarkers[i].show) gmarkers[i].show();
		visibleElements.push(i);
	}
}

// remove all filters used for displaying data in bottomrightcontent
function removeRightFilters() {
	for(activefilter in activeFilters) {
		if(!left_lists.inArray(activefilter)) {
			delete activeFilters[activefilter];
		}
	}
	filter('','');
}

// remove a specific filter
function removeFilter(what,el) {
	if(what != '' && el != '') {
		if(activeFilters[what] && activeFilters[what].inArray(el)) activeFilters[what].remove(el);
		if(activeFilters[what] && activeFilters[what].length == 0) delete activeFilters[what];
	}
}

// generic listing function
function list(what,display) {
	if(what == 'default') what = selectedRightView;
	else selectedRightView = what;

	//debug('what ' + what + ' disp ' + display);
	if(allowed_lists.inArray(what)) { // check that eval doesn't just accept anything
		var which_list = eval(what);
		var out = '';
		if(what == 'formap') 
			out = "<ul id='" + what + "' style='display:" + display + "; padding-left:40px;'>"; 
		else if(left_lists.inArray(what)) 
			out = "<ul id='" + what + "' style='display:" + display + "'>";
		else
			out = "<ul id='" + what + "' class='listimageclosed' style='display:" + display + "'>";
		var list_el;
		for(list_el in which_list) {
			if(what == 'formap') {
			if(visibleElements.inArray(list_el)) {
						out += '<li>';
						if(size != 'widget') out += '<a href="javascript:onmap(' + list_el + ');" style="color:black">';
						if(formap[list_el].firstname != undefined)
							out += formap[list_el].name + ', ' + formap[list_el].firstname;
						else if(formap[list_el].department != undefined && formap[list_el].department != '')
							out += formap[list_el].name + ' - <font color="#415F25">' + formap[list_el].department + '</font>';
						else
							out += formap[list_el].name;
						if(size != 'widget') out += '</a>';
						out += '</li>';
				}
			} else {
				var list_name = which_list[list_el].name;
				var nr = 0;
				var lis = "";
				for(a in visibleElements) { // make sublisting and count the nr of elements
					var a_id = visibleElements[a];
					if(formap[a_id] != undefined && formap[a_id] [what].inArray(list_el)) {
						nr++;
						if(formap[a_id].firstname != undefined)
							lis += '<li><a href="javascript:onmap(' + a_id + ');">' + formap[a_id].name + ', ' + formap[a_id].firstname + '</a></li>';
						else if(formap[a_id].department != undefined && formap[a_id].department != '')
							lis += '<li><a href="javascript:onmap(' + a_id + ');">' + formap[a_id].name + ' - <font color="#415F25">' + formap[a_id].department + '</font></a></li>';
						else
							lis += '<li><a href="javascript:onmap(' + a_id + ');">' + formap[a_id].name + '</a></li>';
					}
				}
				if(nr != 0) {
					out += '<li>';
					if(left_lists.inArray(what)) {
						out += '<a href="javascript:removeAllFilters(); filter(\'' + what + '\',\'' + list_el + '\'); setBottomRightContent(list(\'default\',\'block\')); resizeMap();">(' + nr + ') ' + list_name + '</a>'; 
					} else {
						out += '<a href="javascript:toggleMap(\'' + what + '\',\'' + list_el + '\',\'' + list_name + '\');">' + list_name + ' (' + nr + ')</a>'; 
						out += '<ul id="' + list_name + '" style="display:none;">' + lis + '</ul>';
					}
					out += '</li>';
				}
			}
		}
		out += "</ul>";
		updateStatus(); // write what is listed to bottomrightstatus
	
		return out;
	}
}

/*************************************************
 INTERACTION WITH MAP AND SCREEN 
*************************************************/

// applies a filter and 
// shows / hides an element on screen and on the map
function toggleMap(what, el, idx) {
	if(size != 'widget' && size != undefined) setSideBarInfo('');
	if(idx == '') {
		if(allowed_lists.inArray(what)) {
			what_list = eval(what);
			if(what_list[el]) {
				if(what_list[el].name) var id = what_list[el].name;
				else var id = what_list[el];
			}
		}
	} else var id = idx;
	// check if id is open, if so show stuff
	// if id is not open, hide stuff
	var item = document.getElementById(id);
	if (item && item.style.display == 'block') {
		removeFilter(what,el);
		filter('','');
	} else filter(what,el);	
	toggleDisplay(id);
	updateStatus();
}

// shows / hides a particular element
function toggleDisplay(id) {
	if(size != 'widget' && size != undefined) {
		var el = document.getElementById(id);
		if(el) {
			if(el.style.display == 'none') {
				el.style.display = 'block';
				el.parentNode.style.listStyleImage = 'url(./icons/icon_open.png)';  // todo, be more specific
			}	else if(el.style.display == 'block') {
				el.style.display = 'none';
				el.parentNode.style.listStyleImage = 'url(./icons/icon_closed.png)'; 
			}
		} // else debug('el with id ' + id + ' not found');
	}
}

function showSmallMapContainer(id) {
	if(id == 'smallmapcontainer1') {
		var el = document.getElementById('smallmapcontainer2');
		if(el) {
			el.style.display = 'none';
			el.style.zIndex = 0;
		}
		var el = document.getElementById('smallmapcontainer1');
		if(el) {
			el.style.display = 'block';
			el.style.zIndex = 10;
		}
	} else {
		var el = document.getElementById('smallmapcontainer1');
		if(el) {
			el.style.display = 'none';
			el.style.zIndex = 0;
		}
		var el = document.getElementById('smallmapcontainer2');
		if(el) {
			el.style.display = 'block';
			el.style.zIndex = 10;
			ul = el.getElementsByTagName('ul').item(0);
			if(ul)
				ul.style.display = 'block';
		}
	}
}

// hides a particular element
function hideDisplay(id) {
	var el = document.getElementById(id);
	if(el) el.style.display = 'none';
}

// pick up the click and open the corresponding info window
function onmap(i) {
	GEvent.trigger(gmarkers[i], "click");
}

/*************************************************
 OUTPUT FOR MAP 
*************************************************/
// following function based on 
// http://www.daftlogic.com/Projects/Google-Maps-Distance-Calculator/map.js
function resizeMap(){
	var minLong=999;
	var minLat=999;
	var maxLong=-999;
	var maxLat=-999;
	var mapsize=map.getSpanLatLng();
	var mapWidth=mapsize.width;
	var mapHeight=mapsize.height;
	var baseWidth=mapWidth;
	var baseHeight=mapHeight;
	if(map.getZoomLevel()>0){
		baseWidth/=Math.pow(2,map.getZoomLevel());
		baseHeight/=Math.pow(2,map.getZoomLevel());
	}
	for(var i=0;i<visibleElements.length;i++){
		var visEl = visibleElements[i];
		if(gmarkers[visEl].point.x < minLong) minLong=gmarkers[visEl].point.x;
		if(gmarkers[visEl].point.x > maxLong) maxLong=gmarkers[visEl].point.x;
		if(gmarkers[visEl].point.y < minLat) minLat=gmarkers[visEl].point.y;
		if(gmarkers[visEl].point.y > maxLat) maxLat=gmarkers[visEl].point.y;
	}
	var wZoom=0;
	var w=Math.abs(maxLong-minLong);
	for(var i=1;i<16;i++){
		if(baseWidth>w)break;
		baseWidth*=2;
		wZoom=i;
	}
	var hZoom=0;
	var h=Math.abs(maxLat-minLat);
	for(var i=1;i<16;i++){
		if(baseHeight>h)break;
		baseHeight*=2;
		hZoom=i;
	}
	if(size == 'widget') {
		wZoom +=1;
		hZoom +=1;
	}
	map.centerAndZoom(
		new GPoint((minLong+maxLong)/2,(minLat+maxLat)/2),(wZoom>hZoom?wZoom:hZoom)
	);
}

function addOrganisationMarker(i) {
	var org = formap[i];
	var point = new GLatLng(parseFloat(addresses[org.address].lng),parseFloat(addresses[org.address].lat));
	var marker = new GMarker(point, eval('icon_type_' + types[org.types[0]].name.replace(/ /,"_"))); // todo, only first type now, what if multiple?
	marker.point = point;

	if(size != 'widget' && size != undefined) {
		var pre = "<div class='balloon'>";
		var end = "</div>";

		var vcardOrg = '';
		vcardOrg += '<b>' + org.name + '</b><br/><br/>';
		if(org.department != '') vcardOrg += "<span class='darkgreen'>" + org.department + '</span><br/><br/>';
		vcardOrg += addresses[org.address].address.replace(/\n/g,'<br/>') + '<br/>'

		var orgmeetings = '';
		for(var m in org.meetings) {
			if(meetings[org.meetings[m]] != undefined && meetings[org.meetings[m]] != '') {
				orgmeetings += meetings[org.meetings[m]].name + '<br/>';
			}
		}

		var orgworkgroups = '';
		for(var w in org.workgroups) {
			if(workgroups[org.workgroups[w]] != undefined && workgroups[org.workgroups[w]] != '') {
				orgworkgroups += workgroups[org.workgroups[w]].name + '<br/>';
			}
		}

		var orgpersons = '<iframe src="query.php?org=' + org.name + '&dep=' + org.department + '" frameborder="0" scrolling="auto" height="100px"/>';
	
		// define content of tabs
		if(orgmeetings != '' && orgworkgroups != '') {
			var tabs = [
				new GInfoWindowTab('Organisation', pre + vcardOrg + end),
				new GInfoWindowTab('Meetings', pre + orgmeetings + end),
				new GInfoWindowTab('Workgroups', pre + orgworkgroups + end),
				new GInfoWindowTab('Persons', pre + orgpersons + end)
			];
		} else if(orgmeetings != '' && orgworkgroups == '') {
			var tabs = [
				new GInfoWindowTab('Organisation', pre + vcardOrg + end),
				new GInfoWindowTab('Meetings', pre + orgmeetings + end),
				new GInfoWindowTab('Persons', pre + orgpersons + end)
			];
		} else if(orgworkgroups != '' && orgmeetings == '' ) {
			var tabs = [
				new GInfoWindowTab('Organisation', pre + vcardOrg + end),
				new GInfoWindowTab('Workgroups', pre + orgworkgroups + end),
				new GInfoWindowTab('Persons', pre + orgpersons + end)
			];
		} else {
			var tabs = [
				new GInfoWindowTab('Organisation', pre + vcardOrg + end),
				new GInfoWindowTab('Persons', pre + orgpersons + end)
			];
		}
	
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowTabsHtml(tabs);
			setSideBarInfo(vcardOrg);
		});
	
		GEvent.addListener(marker, "mouseover", function() {
			marker.openInfoWindowTabsHtml(tabs);
			setSideBarInfo(vcardOrg);
		});
	}	
	map.addOverlay(marker);
	gmarkers[i] = marker;
}

function addmarker(i) {
	person = formap[i];
	var vcard = makeVcard(i);
	var point = new GLatLng(parseFloat(addresses[person.address].lng),parseFloat(addresses[person.address].lat));
	var marker = new GMarker(point, eval('icon_role_' + roles[person.roles[0]].name.replace(/ /,"_"))); // todo, only first role now, what if multiple?
	marker.point = point;
	if(size != 'widget' && size != undefined) {
		var persmeetings = '';
		for(var m in person.meetings) {
			if(meetings[person.meetings[m]] != undefined && meetings[person.meetings[m]].name != '') {
				persmeetings += meetings[person.meetings[m]].name + '<br/>';
			}
		}
	
		var persworkgroups = '';
		for(var w in person.workgroups) {
			if(workgroups[person.workgroups[w]] != undefined && workgroups[person.workgroups[w]].name != '') {
				persworkgroups += workgroups[person.workgroups[w]].name + '<br/>';
			}
		}
	
		var organisation = '';
		for(var o in person.organisations) {
			if(organisations[person.organisations[o]] != undefined) {
				if(organisations[person.organisations[o]].department != '') 
					organisation += organisations[person.organisations[o]].department + '<br/>';
				organisation += organisations[person.organisations[o]].name + '<br/>';
				organisation += addresses[organisations[person.organisations[o]].address].address.replace(/\n/g,"<br/>");
			}
		}	
	
		var pre = "<div class='balloon'>";
		var end = "</div>";
	
		if(persmeetings != '' && persworkgroups == '') {
			var tabs = [
					new GInfoWindowTab('Person',pre + vcard + end),
					new GInfoWindowTab('Organisation',organisation),
					new GInfoWindowTab('Meetings',persmeetings)
				];
		} else if(persmeetings == '' && persworkgroups != '') {
			var tabs = [
					new GInfoWindowTab('Person',pre + vcard + end),
					new GInfoWindowTab('Organisation',organisation),
					new GInfoWindowTab('Workgroups',persworkgroups)
				];
		} else if(persmeetings != '' && persworkgroups != '') {
			var tabs = [
					new GInfoWindowTab('Person',pre + vcard + end),
					new GInfoWindowTab('Organisation',organisation),
					new GInfoWindowTab('Meetings',persmeetings),
					new GInfoWindowTab('Workgroups',persworkgroups)
				];
		} else {
			var tabs = [
					new GInfoWindowTab('Person',pre + vcard + end),
					new GInfoWindowTab('Organisation',organisation)
				];
		}
		GEvent.addListener(marker, "click", function() {
			setSideBarInfo(vcard);
			marker.openInfoWindowTabsHtml(tabs);
		});
		GEvent.addListener(marker, "mouseover", function() {
			setSideBarInfo(vcard);
			marker.openInfoWindowTabsHtml(tabs);
		});
	}
	map.addOverlay(marker);
	// store markers
	gmarkers[i] = marker;
}

function makeVcard(i) {
	// name, firstname, title, phone, fax, email, address, roles, address, lat, lng
	var person = formap[i];
	var vcard = '';
	if(person.email != '') vcard += '<a href="mailto:' + person.email + '">';
	vcard += person.name + ', ' + person.firstname;
	if(person.email != '') vcard += '</a>';
	vcard += '<br/><br/><span class="darkgreen">';
	for(r in person.roles) {
		if(roles[person.roles[r]] != undefined) vcard += roles[person.roles[r]].name + '<br/>';
	}
	vcard += '</span><br/>';
	vcard += addresses[person.address].address.replace(/\n/g,'<br/>') + '<br/>';
	if(person.phone != '') vcard += 'phone: ' + person.phone + '<br/>';
	if(person.fax != '') vcard += 'fax: ' + person.fax + '<br/>';
	vcard += '<br/>';
	vcard += '<a href="' + location.href.replace(/\/.*?$/,"") + 'query.php?vcard=' + i + '"><img src="icons/icon_vcard.png"></a>';
	return vcard;
}

/*************************************************
 OUTPUT FOR SCREEN 
*************************************************/

// displays which filters and view are used in div with id=bottomrightstatus
function updateStatus() {
	var myview = '';
	var first = '';
	for(fil in activeFilters) {
		if(fil == 'roles' || fil == 'organisations' || fil == 'formap' || fil == 'types' || fil == 'affiliations') {
			myview += 'toggle=' + activeFilters[fil].join(",") + '&';
		} else myview += fil + '=' + activeFilters[fil].join(",") + '&';
	}
	myview = myview.replace(/&$/,"");
	if(myview != '') myview += '&view=' + selectedRightView;
	else myview = 'view=' + selectedRightView;
	myview += '&what=' + urlwhat;
	myview = location.href.replace(/\/.*?$/,'') + "?" + myview;

	html = '';
	first = selectedRightView;
	if(first == 'formap') { // see which view we are in
		if(formap[1].firstname != undefined) first = 'Persons';
		else first = 'Organisations';
	}
	for(fil in activeFilters) {
		if(left_lists.inArray(fil)) {
			if(activeFilters[fil].length > 1) 
				html += first + ' in all ' + fil;
			else 
				html += first + ' in ' + fil.replace(/s$/,"") + ' ' + eval(fil) [activeFilters[fil]].name;
		}
	}
	if(html == '')
		html += first;

	if(size != 'widget' && size != undefined) {
		setSideBarInfo('');
		setBottomRightStatus(html,myview);
	} else if(size == 'widget') {
		html = "<b>" + html + "</b>";
		html += '<br/><br/>';
		if(allowed_lists.inArray(urlview)) {
			if(urlview != 'formap') html += 'Viewing ' + urlview + ' : <ul>';
			var which_list = eval(urlview);
			if(urltoggle != undefined && urltoggle != '') {
				var toggles = urltoggle.split(",");
				for(var t in toggles) {
					if(typeof toggles[t] != 'function') html += '<li>'+which_list[toggles[t]].name + '</li>';
				}
			} else {
				var stuff = new Array;
				for(var t in which_list) {
					for(a in visibleElements) { // make sublisting and count the nr of elements
						var a_id = visibleElements[a];
						if(urlview != 'formap'){
							if(formap[a_id] != undefined && formap[a_id] [urlview].inArray(t)) {
								stuff.push(which_list[t].name);
							}
						}
					}
				}
				stuff = stuff.arrayUnique();
				if(urlview != 'formap') html += '<li>'+stuff.join("</li><li>")+"</li>";
			}
			if(urlview != 'formap') html += '</ul>';
		}
		setBottomSmallMap(html, myview);
	}
}

function setSideBarInfo(html) {
	el = document.getElementById('sidebarinfo');
	if(html != '') el.style.background = "url(icons/bk_vcard.png)";
	else el.style.background = '';
	el.innerHTML = html;
}

function setBottomLeftContent(html) {
	document.getElementById('bottomleftcontent').innerHTML = html;
}

function setBottomRightHeader(html) {
	document.getElementById('bottomrightheader').innerHTML = '<div style="float:left; color:#B0C830"><b>Browse the NISEnet</b>.</div>  <div style="text-align:right">Select view: ' + html;
}

function setBottomRightStatus(html,link) {
	document.getElementById('bottomrightstatus').innerHTML = '<div style="float:left;"><b>Currently viewing</b>: ' + toUpper(html) + '</div><div style="text-align:right; margin:0; padding:0; color:#D85600;">Link: <a href="' + link + '"><img src="icons/icon_linkmap.png" alt="link" style="margin:0;padding:0"/></a> / <a href="' + link + '&size=widget">w</a></div>';
}

function setBottomRightContent(html) {
	document.getElementById('bottomrightcontent').innerHTML = html;
}

function setBottomSmallMap(html,link) {
	html = html + '<br/>';
	document.getElementById('bottomsmallmap').innerHTML = html;
	if(link != '') setBottomSmallMapLink("<a href='" + link + "'>View large map</a>");
}

function setBottomSmallMapLink(link) {
	document.getElementById('smallmaplink').innerHTML = link;
}

function setSmallMapInfo(html) {
	document.getElementById('smallmapcontainer2').innerHTML = html;
}

function toUpper(string) {
	var first = string.substr(0,1);
	return first.toUpperCase() + string.substr(1,string.length);
}

/*************************************************
 DEBUGGING 
*************************************************/

// write debug info to the debug div
function debug(string) {
	if(logdebug)
		document.getElementById('debug').innerHTML += string + '<br/>';
}

// timer for test purposes
var timer = {
    time: 0,
    now: function(){ return (new Date()).getTime(); },
    start: function(){ this.time = this.now(); },
    since: function(){ return this.now()-this.time; }
}

/*************************************************
 initialize all variables
*************************************************/
function reset() {
	//logdebug = true;
	logdebug = false;
	for(i in gmarkers) { // hide all markers
		if(gmarkers[i].hide) gmarkers[i].hide();
	}
	formap = new Object;
	roles = new Object;
	addresses = new Object;
	meetings = new Object;
	workgroups = new Object;
	organisations = new Object;
	types = new Object;
	affiliations = new Object;
	gmarkers = new Object;
	activeFilters = new Object();
	visibleElements = new Array(); 
	selectedRightView = '';
	if(urlview == '' || urlview == undefined) {
		// debug('reset url vars ' + urlview);
		urlwhat = '';
		urlview = '';
		urlmeetings = '';
		urlworkgroups = '';
		urltoggle = '';
	}
	// put the display to it's initial state
	if(size != 'widget' && size != undefined) {
		map.centerAndZoom(new GPoint(-92,35), 15);
		hideDisplay('legend_role');
		hideDisplay('legend_type');
		setBottomRightHeader('');
		setBottomLeftContent('<br/><img src="icons/loading.gif" alt="loading"/><br/><br/>');
		setBottomRightContent('<br/><center><img src="icons/loading.gif" alt="loading"/></center><br/>');
		setBottomRightStatus('','');
		setSideBarInfo('');
	} else if(size == 'widget') {
		map.centerAndZoom(new GPoint(-92,35), 15);
		setBottomSmallMap('<br/><center><img src="icons/loading.gif" alt="loading"/></center><br/>','');
	}
}

function switchColorOff(id) {
	var el = document.getElementById(id);
	if(el) el.setAttribute('class','');
}
function switchColorOn(id) {
	var el = document.getElementById(id);
	if(el) el.setAttribute('class','selected');
}

/*************************************************
 AJAX STUFF
*************************************************/

// build the query
function doQuery(what) {
	reset();
	urlwhat = what;
	timer.start();
	var uri = 'query.php?what=' + what;
	queryHandler(uri);
	if(what == 'persons') {
		switchColorOn('person_link');
		switchColorOff('organisation_link');
	} else if (what == 'organisations') {
		switchColorOff('person_link');
		switchColorOn('organisation_link');
	}
}

// ajax request
function queryHandler(dataSource) {
	var XMLHttpRequestObject = false;

	if(window.XMLHttpRequest && !(window.ActiveXObject)) {
		XMLHttpRequestObject = new XMLHttpRequest();
		XMLHttpRequestObject.overrideMimeType('text/xml');
	} else if(window.ActiveXObject) {
		XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	if(XMLHttpRequestObject) {
		XMLHttpRequestObject.open('GET',dataSource,true);
		XMLHttpRequestObject.onreadystatechange = function() {
			if(XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
				debug(timer.since() + ' ms to load the data');
				parseResult(XMLHttpRequestObject.responseText); // get's back json response 
			} else {
				if(size != 'widget' && size != undefined) document.getElementById('bottomrightcontent').innerHTML = ''; 
			}
		};
		XMLHttpRequestObject.send(null);
	}
}

// clean JSON response, just to be sure
function cleanupResponseString(response) {
	return response.slice(response.indexOf("{"),response.lastIndexOf("}")+1);
}

