//--------------------------------------------------------------------------------------------------------------------------------
//  GENERIC SHOW/HIDE FUNCTION (PRIMARILY USED FOR '#sidebar')
function showHide(element) {
	if (document.getElementById(element).style.display == 'none') {
		document.getElementById(element).style.display = 'block'
	} else {
		document.getElementById(element).style.display = 'none'
	}
}



//--------------------------------------------------------------------------------------------------------------------------------
//  CROSS-BROWSER (READ: IE-SAFE) METHOD FOR IMPORTING HTML NODES FROM AN XML SOURCE TO THE DOM
function importNode(node, importChildren) { //based on code by Mark Wubben (www.novemberborn.net)
	if (document.importNode) {
		return document.importNode(node, importChildren);
	} else {
		var newNode;

		if (node.nodeType == 1) { //element node
			newNode = document.createElement(node.nodeName);

			for (var i = 0; i<node.attributes.length; i++) {
				newNode.setAttribute(node.attributes[i].name, node.attributes[i].value);
			}

		} else if (node.nodeType == 3) { //textnode
			newNode = document.createTextNode(node.nodeValue);
		}

		if (importChildren && node.hasChildNodes()) {
			for (var oChild = node.firstChild; oChild; oChild = oChild.nextSibling) {
				newNode.appendChild(importNode(oChild, true));
			}
		}

		return newNode;
	}
}



//--------------------------------------------------------------------------------------------------------------------------------
//  GENERIC ZOOM FUNCTION
function zoom(map, level) {
	//determine the new preset level based on the current zoomlevel
	if (level == 'out') {
		switch (parseInt(map.getZoom())) {
			case 17:
				presetLevel = 2;
				break;
			case 15:
				presetLevel = 3;
				break;
			case 13:
				presetLevel = 4;
				break;
			default:
				return;
		}

	//determine the new preset level based on the current zoomlevel
	} else if (level == 'in') {
		switch (parseInt(map.getZoom())) {
			case 15:
				presetLevel = 1;
				break;
			case 13:
				presetLevel = 2;
				break;
			case 12:
				presetLevel = 3;
				break;
			default:
				return;
		}

	//number is clicked. preset level is the number in level
	} else {
		presetLevel = level;
	}

	//determine new map zoomlevel based on preset level. closest level hides the district borders.
	switch (presetLevel) {
		case 1:
			newLevel = 17;
			break;
		case 2:
			newLevel = 15;
			break;
		case 3:
			newLevel = 13;
			break;
		case 4:
			newLevel = 12;
			break;
	}

	//zoom the map to the new level, set all zoom level imgs to inactive and set the one for the current level active
	map.setZoom(newLevel);
	setZoomImgsInactive();
	document.getElementById('zoom' + presetLevel).className = ' active';
}

//-------------------------------------------------------------------------------------------------------------------------------
//	SET ALL ZOOM LEVEL IMGS INACTIVE (USED PRIMARILY BIJ ZOOM() )
function setZoomImgsInactive() {
	mapCtrls = document.getElementById('mapcontrols').getElementsByTagName('li');

	for (i=0; i<mapCtrls.length; i++) {
		strId = mapCtrls[i].id.match('zoom[0-9]+');
		if (strId != null) {
			mapCtrls[i].className = '';
		}
	}
}




//--------------------------------------------------------------------------------------------------------------------------------
//  CONVERT AN ELEMENT TO WORKABLE MAP AND PLACE CONTROLLERS, CENTERPOINT AND ZOOMLEVEL
function prepareMap(mapElement, mapType, ctrls, coordinates, zoomLevel) {
	var map, districtsLayer, customMap;

	//create custom tilelayer
	districtsLayer = new GTileLayer(new GCopyrightCollection(""), 12, 17);
	districtsLayer.getTileUrl = function(point, zoom) {
		return '/img/districttiles/index.php?x=' + point.x + '&y=' + point.y + '&z=' + (17 - zoom);
	}
	districtsLayer.isPng = function () { return true}

	//create the custom maptype. Copy the one (and only) layer from the satellite and set ours on top of that
	customMap = new GMapType([G_SATELLITE_MAP.getTileLayers()[0], districtsLayer], G_SATELLITE_MAP.getProjection(), 'Satelliet', {maxResolution:17, minResolution:12, errorMessage:"Niet beschikbaar op dit zoomniveau"});

	//set the buttontext for G_NORMAL_MAP to Dutch (from "Map" to "Kaart")
	G_NORMAL_MAP['ng'] = 'Kaart';

	//create the map
	map = new GMap2(mapElement, {mapTypes:[G_NORMAL_MAP, customMap]});

	//add the custom map to the maptypes
	map.addMapType(customMap);

	if (coordinates != '') {
		map.setCenter(coordinates);
	}

	if (zoomLevel != '') {
		map.setZoom(parseInt(zoomLevel));
	}

	//if maptype is given set it to either custom, map, satelite or hybrid else set it to sat
	if (mapType != '' && mapType != null) {
		if (mapType == 'custom') {
			map.setMapType(customMap);
		} else if (mapType == 'sat') {
			map.setMapType(G_SATELLITE_MAP);
		} else if (mapType == 'hybrid') {
			map.setMapType(G_HYBRID_MAP);
		} else if (mapType == 'map') {
			map.setMapType(G_NORMAL_MAP);
		}
	} else {
		map.setMapType(G_SATELLITE_MAP);
	}

	//add all the controls in the array ctrls to the map
	if (ctrls != '' && ctrls != null) {
		for (i=0; i<ctrls.length; i++) {
			map.addControl(ctrls[i]);
		}
	}

	return map;
}



//--------------------------------------------------------------------------------------------------------------------------------
//  MAKE AN AJAX REQUEST AND RETURN THE RESULTING DOM
function makeRequest(url, method, parameters, format) {
	method     = method || 'GET';
	parameters = (method == 'POST') ? parameters : null;
	format     = format || 'xml'; //can be 'text' or 'xml'

	xmlHttp.open(method, url, false);

	xmlHttp.send(parameters);

	if (format == 'xml') {
		return xmlHttp.responseXML;
	} else if (format == 'text') {
		return xmlHttp.responseText;
	}
}



//--------------------------------------------------------------------------------------------------------------------------------
//  TURN ALL ITEMGROUPS ON OR OFF
function switchAllItemGroups (map, mode) {
	//force all itemgroups to show
	if (mode == 'show') {
		for (itemgroup in itemGroups) {
			showHideItemGroup(map, itemgroup, 'show');

			if (document.getElementById(itemgroup)) {
				document.getElementById(itemgroup).checked = true;
			}
		}

		document.getElementById('switchitemgroups').value = 'Zet alle thema\'s uit';

	//force all itemgroups to hide
	} else if (mode == 'hide') {
		for (itemgroup in itemGroups) {
			showHideItemGroup(map, itemgroup, 'hide');

			if (document.getElementById(itemgroup)) {
				document.getElementById(itemgroup).checked = false;
			}
		}

		document.getElementById('switchitemgroups').value = 'Zet alle thema\'s aan';

	//switch state of all itemgroups
	} else {
		for (itemgroup in itemGroups) {
			showHideItemGroup(map, itemgroup);

			if (document.getElementById(itemgroup)) {
				if (document.getElementById(itemgroup).checked == true) {
					document.getElementById(itemgroup).checked = false;
				} else {
					document.getElementById(itemgroup).checked = true;
				}
			}
		}
	}
}


//--------------------------------------------------------------------------------------------------------------------------------
//  GET ALL THE CONFIG OPTIONS
function getConfig() {
	configXML  = makeRequest('/xml/config.xml');
	minZoomLvl = configXML.getElementsByTagName('zoomlevels')[0].getAttribute('min');
	maxZoomLvl = configXML.getElementsByTagName('zoomlevels')[0].getAttribute('max');

	//if variable startPoint is not already set, set it here along with the default zoom level
	if (typeof(startPoint) != 'object') {
		startLng   = parseFloat(configXML.getElementsByTagName('startpoint')[0].getAttribute('lng'));
		startLat   = parseFloat(configXML.getElementsByTagName('startpoint')[0].getAttribute('lat'));
		startPoint = new GLatLng(startLat, startLng);
		defZoomLvl = configXML.getElementsByTagName('zoomlevels')[0].getAttribute('def');
	}
}



//--------------------------------------------------------------------------------------------------------------------------------
//  GET ALL THE DIFFERENT AREAS OF THE CITY
function getAreas() {
	areasXML   = makeRequest('/xml/areas.xml');
	areasGroup = areasXML.getElementsByTagName('area');

	//get the scriptname, screenname and location of each district and place it in the areas object
	for (i=0; i<areasGroup.length; i++) {
		lat   = areasGroup[i].getElementsByTagName('position')[0].getAttribute('lat');
		lng   = areasGroup[i].getElementsByTagName('position')[0].getAttribute('lng');
		scriptName = areasGroup[i].getElementsByTagName('scriptname')[0].firstChild.data;
		screenName = areasGroup[i].getElementsByTagName('screenname')[0].firstChild.data;

		areas[scriptName] = new Object();
		areas[scriptName]['screenName'] = screenName;
		areas[scriptName]['point'] = new GLatLng(lat, lng);
	}
}



//--------------------------------------------------------------------------------------------------------------------------------
//  DISPLAY THE BALLOON OF A CANDIDATE
function showCandidate(map, id) {
	//iterate through all the markers on the map. if the id attribute of it is the same as the id attribute given to this function
	//pan the map to the location of the marker, zoom the map to the second level and trigger (simulate) a click event on the marker
	//to open the balloon

	showHideItemGroup(map, 'pvda', 'show');
	document.getElementById('pvda').checked = true;

	setTimeout(function() {
		for (i=0; i<markers.length; i++) {
			if (markers[i].id == id) {
				map.setCenter(markers[i].getPoint());
				map.setZoom(15);
				GEvent.trigger(markers[i], 'click');

				//somehow the map needs some time to proces the panning and zooming, so we wait 0.1 secs to continue
				setTimeout(function () {
					setZoomImgsInactive();
					document.getElementById('zoom2').className = ' active';
				}, 100);

				getItem(id);
				break;
			}
		}
	}, 100);
}



//--------------------------------------------------------------------------------------------------------------------------------
//  GET ALL THE ITEMS AND PLACE THEM ON THE MAP
function getItems(map) {
	itemsXML   = makeRequest('/xml/items.xml.php');
	itemsGroup = itemsXML.getElementsByTagName('item');

	for (i=0; i<itemsGroup.length; i++) {
		//grab info from XML DOM item node
		id    = itemsGroup[i].getAttribute('id');
		group = itemsGroup[i].getElementsByTagName('itemgroup')[0].firstChild.data;
		lat   = parseFloat(itemsGroup[i].getElementsByTagName('position')[0].getAttribute('lat'));
		lng   = parseFloat(itemsGroup[i].getElementsByTagName('position')[0].getAttribute('lng'));
		title = itemsGroup[i].getElementsByTagName('title')[0].firstChild.data;

		marker = new GMarker(new GLatLng(lat, lng), itemGroups[group]['icon']);
		marker.id = id;        //database id of the item associated with the marker
		marker.orgY = lat;     //the latitude coordinate of the marker. used to let the marker reappear on the map
		marker.title = title;  //the title of the item used in the balloon when it opens
		marker.group = group;  //needed to determine the itemgroup a marker belongs to

		//add code that opens balloon on click event of the marker
		GEvent.addListener(marker, "click", function () {
			this.openInfoWindowHtml('<div id="infowindow"><strong>' + this.title + '</strong><br /><br /><a href="#headline" onclick="getItem('+this.id+')">Lees meer hierover</a></div>');
		});

		markers.push(marker);
		map.addOverlay(markers[markers.length - 1]);
	}
}



//--------------------------------------------------------------------------------------------------------------------------------
//  CREATE FUNCTION FOR MULTIMEDIA CLICK EVENTS
function createFunction (fileType, fileName, id) {
	return function () {
		mediaPopup(fileType, fileName, id);
	}
}


//--------------------------------------------------------------------------------------------------------------------------------
//  GET ALL THE INFO ON A SPECIFIC ITEM
function getItem(strId) {
	//if the elements that get new content are not present, create them
	if (!document.getElementById('meta') && !document.getElementById('headline')) {
		//create a horizontal rule	and place in the DOM as child of #content
		horRule  = document.createElement('div');
		horRule.className = 'hr';
		horRule.appendChild(document.createElement('hr'));
		document.getElementById('content').appendChild(horRule);

		//create headline <h3> and place in the DOM as child of #content
		head = document.createElement('h3');
		head.appendChild(document.createTextNode(''));
		head.id = 'headline';
		document.getElementById('content').appendChild(head);

		//create <p> #meta and permalink and place in the DOM as child of #content
		meta = document.createElement('p');
		meta.id = 'meta';
		postUrl = document.createElement('a');
		postUrl.appendChild(document.createTextNode('Gebruik deze link als u naar dit item wilt verwijzen'));
		meta.appendChild(postUrl);
		document.getElementById('content').appendChild(meta);
	}

	//place some stuff from XML in variables
	itemXML    = makeRequest('/xml/item.xml.php?id=' + strId);
	title      = itemXML.getElementsByTagName('title')[0].firstChild.data;
	eleContent = itemXML.getElementsByTagName('post')[0];
	lat        = itemXML.getElementsByTagName('position')[0].getAttribute('lat');
	lng        = itemXML.getElementsByTagName('position')[0].getAttribute('lng');
	fullUrl    = itemXML.getElementsByTagName('fullurl')[0].firstChild.data;
	eleMeta    = document.getElementById('meta');
	files      = itemXML.getElementsByTagName('files')[0].childNodes;

	//place title in <h3> and assign the correct class based on the itemgroup of the icon
	for (i=0; i<markers.length; i++) {
		if (markers[i].id == strId) {
			itemGroup = markers[i].group;
			document.getElementById('headline').className = itemGroup;
			break;
		}
	}

	document.getElementById('headline').firstChild.data = title;  //fill headline
	eleMeta.getElementsByTagName('a')[0].href = fullUrl;          //fill permalink
	eleMeta.getElementsByTagName('a')[0].id = 'permalink';

	//kick everything out the DOM tree that is placed after p#meta
	while (document.getElementById('content').lastChild.nodeName != 'P' || document.getElementById('content').lastChild.id != 'meta') {
		document.getElementById('content').removeChild(document.getElementById('content').lastChild);
	}

	//create minimap and place marker
	eleMiniMap = document.createElement('div');
	eleMiniMap.id = 'minimap';
	document.getElementById('content').appendChild(eleMiniMap);
	centerPoint = new GLatLng(lat, lng);
	miniMap = prepareMap(document.getElementById('minimap'), null, null, centerPoint, 16);
	miniMap.disableDragging();

	//create new icon for in the center of the minimap
	miniMapIcon = new GIcon();
	miniMapIcon.image = '/img/minimap_marker_icon.png';
	miniMapIcon.iconSize = new GSize(33, 33);
	miniMapIcon.iconAnchor = new GPoint(16,16);

	marker = new GMarker(centerPoint, miniMapIcon);
	miniMap.addOverlay(marker);

	eleText = document.createElement('div');
	eleText.id = 'text';

	/*place each HTML node that is in <post> as child of #content
	for (i=0; i<eleContent.childNodes.length; i++) {
		eleText.appendChild(importNode(eleContent.childNodes[i], true));
	}*/

	eleText.innerHTML += eleContent.firstChild.data;

	document.getElementById('content').appendChild(eleText);

	//create link to the corresponding chapter in the election plans
	readChapter = document.createElement('p');

	//create a link for each chapter where the item corresponds to
	if (itemGroups[itemGroup]['links']) {
		for (chapter in itemGroups[itemGroup]['links']) {
			readChapterLink = document.createElement('a');
			readChapterLink.href = itemGroups[itemGroup]['links'][chapter];
			readChapterLink.target = '_blank';
			readChapterLinkText = document.createTextNode('Lees het hoofdstuk "' + chapter + '" in het verkiezingsprogramma');
			readChapterLink.appendChild(readChapterLinkText);
			readChapter.appendChild(readChapterLink);
			readChapter.appendChild(document.createElement('br'));
		}

		document.getElementById('content').appendChild(readChapter);
	}

	if (files.length > 0) {
		//create mark-up for multimedia stuff
		mmHeading = document.createElement('h4');
		mmHeading.appendChild(document.createTextNode('Beelden bij dit item'));
		document.getElementById('content').appendChild(mmHeading);

		mmParagraph = document.createElement('p');

		//make some stuff for the things to be put in.
		for (i=0; i<files.length; i++) {
			thumb = document.createElement('span');
			thumb.className = 'thumb';

			thumbImg = document.createElement('img');
			thumbImg.src = '/upload/images/' + files[i].lastChild.firstChild.data;
			thumbImg.alt = 'Thumbnail';

			typeIndicator = document.createElement('span');
			typeIndicator.className = files[i].getAttribute('type');

			popupFunction = createFunction(files[i].getAttribute('type'), files[i].firstChild.firstChild.data, strId); //giving the item id so the popup can get the title
			thumbImg.onclick = popupFunction;

			thumb.appendChild(thumbImg);
			thumb.appendChild(typeIndicator);
			mmParagraph.appendChild(thumb);
		}

		document.getElementById('content').appendChild(mmParagraph);
	}

	//create a new footer and chuck out the old one. Needed to workaround the crappy Trident engine in IE (it has refresh issues for absolute positioned elements)
	newFooter = document.createElement('p');
	newFooter.id = 'footer';
	swisLink = document.createElement('a');
	swisLink.href = 'http://swis.nl/';
	swisLink.title = '...met een snufje Plerion';
	swisLink.appendChild(document.createTextNode('SWIS'));
	googleLink = document.createElement('a');
	googleLink.href = 'http://maps.google.com/';
	googleLink.appendChild(document.createTextNode('Google Maps'));
	newFooter.appendChild(document.createTextNode('Powered by '));
	newFooter.appendChild(swisLink);
	newFooter.appendChild(document.createTextNode(' en '));
	newFooter.appendChild(googleLink);

	if (document.getElementById('footer')) {
		document.getElementById('content').removeChild(document.getElementById('footer'));
	}

	document.getElementById('content').appendChild(newFooter);

	//closes the InfoWindow when the content is generated
	theMap.closeInfoWindow();

	document.getElementById('headline').scrollIntoView(true);
}



//--------------------------------------------------------------------------------------------------------------------------------
//  GET ALL THE DIFFERENT ITEMGROUPS
function getItemGroups() {
	itemGroupsXML = makeRequest('/xml/itemgroups.xml');
	groups        = itemGroupsXML.getElementsByTagName('itemgroup');

	for (i=0; i<groups.length; i++) {
		//grab info from XML DOM itemgroup node
		scriptName = groups[i].getElementsByTagName('scriptname')[0].firstChild.data;
		screenName = groups[i].getElementsByTagName('screenname')[0].firstChild.data;
		iconUrl    = groups[i].getElementsByTagName('icon')[0].firstChild.data;
		iconWidth  = groups[i].getElementsByTagName('icon')[0].getAttribute('width');
		iconHeight = groups[i].getElementsByTagName('icon')[0].getAttribute('height');
		groupLinks = groups[i].getElementsByTagName('links')[0].childNodes;

		if (groups[i].getElementsByTagName('shadow')[0].firstChild) { //check if <shadow> has an url
			if (groups[i].getElementsByTagName('shadow')[0].firstChild.data != '') {
				shadowUrl    = groups[i].getElementsByTagName('shadow')[0].firstChild.data;
				shadowWidth  = groups[i].getElementsByTagName('shadow')[0].getAttribute('width');
				shadowHeight = groups[i].getElementsByTagName('shadow')[0].getAttribute('height');
			}
		}

		//place group info in object including icon
		itemGroups[scriptName] = new Object();
		itemGroups[scriptName]['scriptname'] = scriptName;
		itemGroups[scriptName]['screenname'] = screenName;

		if (groupLinks.length > 0) {
			itemGroups[scriptName]['links'] = new Object;

			for (j=0; j<groupLinks.length; j++) {
				if (groupLinks[j].nodeName != '#text') {
					itemGroups[scriptName]['links'][groupLinks[j].getAttribute('chapter')] = groupLinks[j].firstChild.data;
				}
			}
		}

		//make an GIcon object for the itemGroup
		itemGroups[scriptName]['icon']       = new GIcon();
		itemGroups[scriptName]['icon'].image = iconUrl;
		itemGroups[scriptName]['icon'].iconSize = new GSize(iconWidth, iconHeight);

		if (groups[i].getElementsByTagName('shadow')[0].firstChild) {
			if (groups[i].getElementsByTagName('shadow')[0].firstChild.data != '') {
				itemGroups[scriptName]['icon'].shadow     = shadowUrl;
				itemGroups[scriptName]['icon'].shadowSize = new GSize(shadowWidth, shadowHeight);
			}
		}

		itemGroups[scriptName]['icon'].iconAnchor = new GPoint(Math.round(iconWidth / 2), Math.round(iconHeight / 2));
		itemGroups[scriptName]['icon'].infoWindowAnchor = new GPoint(Math.round(iconWidth / 2), 1);
	}
}



//--------------------------------------------------------------------------------------------------------------------------------
//  HIDE OR SHOW AN ITEMGROUP
function showHideItemGroup(map, group, mode) {
	if (mode) {
		//mode set to 'show' forcefully show items
		if (mode == 'show') {
			for (i=0; i<markers.length; i++) {
				if (markers[i].group == group) {
					markers[i].setPoint(new GLatLng(markers[i].orgY, markers[i].getPoint().lng()));
					markers[i].redraw(true);
				}
			}

		//mode set to 'hide' forcefully hide items
		} else if (mode == 'hide') {
			for (i=0; i<markers.length; i++) {
				if (markers[i].group == group) {
					markers[i].setPoint(new GLatLng(-100, markers[i].getPoint().lng()));
					markers[i].redraw(true);
				}
			}
		}

	//mode not set. determine state and switch to show/hide
	} else {
		for (i=0; i<markers.length; i++) {
			if (markers[i].group == group) {
				if (markers[i].getPoint.lat() == -100) {
					markers[i].setPoint(new GLatLng(markers[i].orgY, markers[i].getPoint().lng()));
				} else {
					markers[i].setPoint(new GLatLng(-100, markers[i].getPoint().lng()));
				}

				markers[i].redraw(true);
			}
		}
	}
}



//--------------------------------------------------------------------------------------------------------------------------------
//  DO AJAX SEARCH FOR POSTCODE USING XML-RPC
function searchPostcode(map, postcode) {
	infoXML = makeRequest('/xml/postcode.xml.php?postcode=' + postcode);

	if (infoXML.firstChild.nodeName == 'error') {
		alert(infoXML.firstChild.firstChild.data);
	} else if (infoXML.firstChild.nodeName == 'address') {
		street = infoXML.getElementsByTagName('street')[0].firstChild.data;
		genPC  = infoXML.getElementsByTagName('street')[0].getAttribute('postcode');
		lat    = infoXML.getElementsByTagName('position')[0].getAttribute('lat');
		lng    = infoXML.getElementsByTagName('position')[0].getAttribute('lng');
		var closeTimeout = 3; //seconds to keep infoWindow open

		zoom(map, 1);
		postcodePoint = new GLatLng(lat - 0.001, lng);
		map.panTo(postcodePoint);
		map.openInfoWindowHtml(postcodePoint, '<div id="infowindow"><p>' + street + '<br />' + genPC + ' Leiden.</p><p id="closein">Sluit in ' + closeTimeout + ' seconden</p></div>');
		setTimeout(function () {map.closeInfoWindow()}, closeTimeout * 1000);
	}
}



//---------------------------------------------------------------------------------------------------------------------------------
//  CREATE A POPUP WINDOW FOR THE CLICKED MEDIA FILE
function mediaPopup(fileType, fileName, id) {
	//if window is still open, close it
	if (mediaWin != null && mediaWin.closed == false) {
		mediaWin.close();
	}

	if (fileType == 'image') {
		iHeight = 300;
		iWidth  = 400;
	} else if (fileType == 'video') {
		iWidth  = 600;
		iHeight = 400;
	} else {
		return;
	}

	iLeft = (screen.width - iWidth) / 2;
	iTop  = (screen.height - iHeight) / 2;

	url = '/media.php?file=' + fileName + '&type=' + fileType
	url += (id != null) ? '&id=' + id : '';

	if (window.createPopup == undefined) { //just checking for compliant/non-compliant browsers
		//open for non-IE browsers
		mediaWin = window.open(url, 'mediaWindow', 'dependent=no, width=' + iWidth + ', height=' + iHeight + ', left=' + iLeft + ', top=' + iTop);
	} else {
		//open for IE
		mediaWin = window.open(url, 'mediaWindow', 'directories=no, scrollbars=no, toolbar=no, menubar=no, location=no, resizable=no, status=no, width=' + iWidth + ', height=' + iHeight + ', left=' + iLeft + ', top=' + iTop);
	}
}

//---------------------------------------------------------------------------------------------------------------------------------
//  CUSTOM GCONTROL FOR PANNING THE MAP IN 8 WIND DIRECTIONS
function compassControl() {}

compassControl.prototype = new GControl();

compassControl.prototype.initialize = function(map) {
	var container = document.createElement('div');

	nwButton = document.createElement('div');
	nButton = document.createElement('div');
	neButton = document.createElement('div');
	eButton = document.createElement('div');
	seButton = document.createElement('div');
	sButton = document.createElement('div');
	swButton = document.createElement('div');
	wButton = document.createElement('div');

	nwButton.className = 'compasscontrolnw';
	nButton.className  = 'compasscontroln';
	neButton.className = 'compasscontrolne';
	eButton.className  = 'compasscontrole';
	seButton.className = 'compasscontrolse';
	sButton.className  = 'compasscontrols';
	swButton.className = 'compasscontrolsw';
	wButton.className  = 'compasscontrolw';

	container.appendChild(nwButton);
	container.appendChild(nButton);
	container.appendChild(neButton);
	container.appendChild(eButton);
	container.appendChild(seButton);
	container.appendChild(sButton);
	container.appendChild(swButton);
	container.appendChild(wButton);

	GEvent.addDomListener(nwButton, 'click', function() {
		centerPoint = map.getCenter();
		halfWidth   = map.getBounds().toSpan().lng() / 2;
		halfHeight  = map.getBounds().toSpan().lat() / 2;

		map.panTo(new GLatLng(centerPoint.lat() + halfHeight, centerPoint.lng() - halfWidth));
	});

	GEvent.addDomListener(nButton, 'click', function() {
		centerPoint = map.getCenter();
		halfHeight  = map.getBounds().toSpan().lat() / 2;

		map.panTo(new GLatLng(centerPoint.lat() + halfHeight, centerPoint.lng()));
	});

	GEvent.addDomListener(neButton, 'click', function() { map.panTo(map.getBounds().getNorthEast()); });

	GEvent.addDomListener(eButton, 'click', function() {
		centerPoint = map.getCenter();
		halfWidth   = map.getBounds().toSpan().lng() / 2;

		map.panTo(new GLatLng(centerPoint.lat(), centerPoint.lng() + halfWidth));
	});

	GEvent.addDomListener(seButton, 'click', function() {
		centerPoint = map.getCenter();
		halfWidth   = map.getBounds().toSpan().lng() / 2;
		halfHeight  = map.getBounds().toSpan().lat() / 2;

		map.panTo(new GLatLng(centerPoint.lat() - halfHeight, centerPoint.lng() + halfWidth));
	});

	GEvent.addDomListener(sButton, 'click', function() {
		centerPoint = map.getCenter();
		halfHeight  = map.getBounds().toSpan().lat() / 2;

		map.panTo(new GLatLng(centerPoint.lat() - halfHeight, centerPoint.lng()));
	});

	GEvent.addDomListener(swButton, 'click', function() { map.panTo(map.getBounds().getSouthWest()); });

	GEvent.addDomListener(wButton, 'click', function() {
		centerPoint = map.getCenter();
		halfWidth   = map.getBounds().toSpan().lng() / 2;

		map.panTo(new GLatLng(centerPoint.lat(), centerPoint.lng() - halfWidth));
	});

	map.getContainer().appendChild(container);
	return container;
}

compassControl.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(5, 5));
}