/** 
 *    Author: Arne Eckhoff <eckhoff@kdo.de>
 *      Date: 24.01.2008 13:12:14
 *   Project: KIM - Gis Bürgerclient
 * Copyright: 2008 Kommunale Datenverarbeitung Oldenburg (KDO)
 *      Link: http://www.kdo.de/
 */

//* global variables
//*******************************
var map; // to access the google map
var geocoder; // access Geocoder options of Google API
var gdir = null; // gDirections for routing
var umKreis1 = null; // Properties for radial search
var umKreis2 = null; // Properties for radial search


//* variables specially for the mapfunctions tab
//*******************************
//Is the user currently using the routing functions?
var isRouting = false;
//Vars for Eventlistening
var routingEvent1;
var measureAreaEvent1;
var meetingPointEvent;
//var for the marker of the meeting point on the map	
var meetingPointMarker = null;
var meetingPoint = null;
//marker manager for the search results
var markerSuche = new Array();
//marker manager for the results of radial search
var markerSucheUmkreis = new Array();
//vars for the circles of radial search...
var BDCCCircleId;
var BDCCCircleSvgRoot;
//array of points for the route
var routingPoints;


//* Functions
//*******************************


//Adapter method for addAdresse()
//You can use this method to add an address with points instead of 'Street, city'
function addAdresseXY(x, y, URL, iconURL, arrMarker, id) {
	addAdresse(new GLatLng(x, y), URL, iconURL, arrMarker, id);
}


//Centers the map on the stated point and current zoom level
function setMapCenter(point) {
	setMapCenterZoom(point,map.getZoom());
}


//Centers the map on the stated point but also zoom to the stated zoom level
//You have to reset the offset in relation to the zoom level. Otherwise the 
//bubble would be underneath the menubar or outside of the map
function setMapCenterZoom(point,zoom) {
	var offset = 0;
	if(zoom==14) offset=0.015;
	if(zoom==13) offset=0.030;
	if(zoom==12) offset=0.055;
	if(zoom==11) offset=0.110;
	if(zoom==10) offset=0.215;
	if(zoom==9) offset=0.440;
	if(zoom==8) offset=0.880;
	if(zoom==7) offset=1.760;
	if(zoom==6) offset=3.420;
	try {
		map.setCenter(new GLatLng((point.y+offset), (point.x)),zoom);
	} catch (e) {}
}


//Select the entry in the result list, if the corresponding marker was clicked
function selectEntryInList(id) {
	// determine, which list and menu is active ?
	if(1==2) {// nothing....

	} else if(selectedTab=="categorys" && wasShownRubrikSearch) {
		var iframe = document.getElementById('IFrubrikenSuchen');
		iframe.contentWindow.document.getElementById('rubrikEintrag'+id).style.backgroundColor = "#e5ebf1";
		if(parent.selectedRubrikSearch>0 && parent.selectedRubrikSearch!=id) {
			iframe.contentWindow.document.getElementById('rubrikEintrag'+parent.selectedRubrikSearch).style.backgroundColor = "#ffffff";
		}
		parent.selectedRubrikSearch = id;


	} else if(selectedTab=="categorys" && wasShownRubrikList) {
		var iframe = document.getElementById('IFrubrikenAdressen');
		iframe.contentWindow.document.getElementById('rubrikEintrag'+id).style.backgroundColor = "#e5ebf1";
		if(parent.selectedRubrik>0 && parent.selectedRubrik!=id) {
			iframe.contentWindow.document.getElementById('rubrikEintrag'+parent.selectedRubrik).style.backgroundColor = "#ffffff";
		}
		parent.selectedRubrik = id;


	} else if(selectedTab=="branches" && wasShownBrancheSearch) {
		// Branch search results list is visible
		document.getElementById('firma'+id).style.backgroundColor = "#e5ebf1";
		if(selectedCompanySearch>0 && selectedCompanySearch!=id) {
			document.getElementById('firma'+selectedCompanySearch).style.backgroundColor = "#ffffff";
		}
		selectedCompanySearch = id;


	} else if(selectedTab=="branches" && wasShownBrancheList) {
		// Branch list is visible
		document.getElementById('brancheEintrag'+id).style.backgroundColor = "#e5ebf1";
		if(selectedBrancheEintrag>0 && selectedBrancheEintrag!=id) {
			document.getElementById('brancheEintrag'+selectedBrancheEintrag).style.backgroundColor = "#ffffff";
		}
		selectedBrancheEintrag = id;


	} else if(selectedTab=="vereine" && wasShownVereinSearch) {
		// verein search results list is visible
		var iframe = document.getElementById('IFvereinSuchen');
		iframe.contentWindow.document.getElementById('verein'+id).style.backgroundColor = "#e5ebf1";
		if(selectedVereinSearch>0 && selectedVereinSearch!=id) {
			iframe.contentWindow.document.getElementById('verein'+selectedVereinSearch).style.backgroundColor = "#ffffff";
		}
		selectedVereinSearch = id;


	} else if(selectedTab=="vereine" && wasShownVereinList) {
		// verein list is visible
		var iframe = document.getElementById('IFvereinAdressen');
		iframe.contentWindow.document.getElementById('vereinEintrag'+id).style.backgroundColor = "#e5ebf1";
		if(selectedVereinList>0 && selectedVereinList!=id) {
			iframe.contentWindow.document.getElementById('vereinEintrag'+selectedVereinList).style.backgroundColor = "#ffffff";
		}
		selectedVereinList = id;


	} else if(selectedTab=="events") {
		// event list is visible
		var iframe = document.getElementById('IFevents');
		iframe.contentWindow.document.getElementById('veranstaltung'+id).style.backgroundColor = "#e5ebf1";
		if(selectedEventEintrag>0 && selectedEventEintrag!=id) {
			iframe.contentWindow.document.getElementById('veranstaltung'+selectedEventEintrag).style.backgroundColor = "#ffffff";
		}
		selectedEventEintrag = id;

	}  else if(selectedTab=="accomodation" && wasShownUnterkunftSearch) {
		var iframe = document.getElementById('IFunterkunftSuchen');
		iframe.contentWindow.document.getElementById('unterkunftEintrag'+id).style.backgroundColor = "#e5ebf1";
		if(parent.selectedUnterkunftSearch>0 && parent.selectedUnterkunftSearch!=id) {
			iframe.contentWindow.document.getElementById('unterkunftEintrag'+parent.selectedUnterkunftSearch).style.backgroundColor = "#ffffff";
		}
		parent.selectedUnterkunftSearch = id;
	} else if(selectedTab=="accomodation" && wasShownUnterkunftList) {
		var iframe = document.getElementById('IFunterkunftAdressen');
		iframe.contentWindow.document.getElementById('unterkunftEintrag'+id).style.backgroundColor = "#e5ebf1";
		if(parent.selectedUnterkunft>0 && parent.selectedUnterkunft!=id) {
			iframe.contentWindow.document.getElementById('unterkunftEintrag'+parent.selectedUnterkunft).style.backgroundColor = "#ffffff";
		}
		parent.selectedUnterkunft = id;
	}
}

function addAdresse(point, URL, iconURL, arrMarker, id) {
	var icon = new GIcon(baseIcon);
	if(iconURL!="") icon.image = iconURL;

	URL = '<iframe frameborder="0" width="400" height="300" src="' + URL + '"></iframe>';
		
	var marker = new GMarker(point, icon);
	GEvent.addListener(marker, "click", function () { 
		setMapCenter(point);
		marker.openInfoWindowHtml(URL); 

		// select the entry in list
		selectEntryInList(id);

		if(selectedTab=="vereine" && document.getElementById("vereineListe").style.display!="none") $("#vereineListe").hideSlow();
		if(selectedTab=="branches" && document.getElementById("branchenListe").style.display!="none") $("#branchenListe").hideSlow();
		if(selectedTab=="categorys" && document.getElementById("myRubriken").style.display!="none") $("#myRubriken").hideSlow();
		if(selectedTab=="accomodation" && document.getElementById("myUnterkunft").style.display!="none") $("#myUnterkunft").hideSlow();
	});
	if(id=="") {
		arrMarker.push(marker);
	} else {
		arrMarker[id] = marker;
	}
	map.addOverlay(marker);
}

function addNoGeoAdresse(addresse, URL, arrMarker, id, iconURL) {
	addNoGeoAdresse(addresse, URL, arrMarker, id, iconURL, showBubble, false,0);
}


function addNoGeoAdresse(addresse, URL, arrMarker, id, iconURL, showBubble,zoomLevel) {
	addresse = (addresse);
	addresse = addresse.replace(/&ouml;/g,"ö");
	addresse = addresse.replace(/&uuml;/g,"ü");
	addresse = addresse.replace(/&auml;/g,"ä");
	addresse = addresse.replace(/&szlig;/g,"ß");
	geocoder.getLatLng(addresse + ", Germany",
			function(point) {
		if (point) {
			var icon = new GIcon(baseIcon);
			if(iconURL!="") icon.image = iconURL;
			var marker = new GMarker(point, icon);
			URL = '<iframe frameborder="0" width="400" height="300" src="' + URL + '"></iframe>';
			GEvent.addListener(marker, "click", function () { 
				setMapCenter(point);
				marker.openInfoWindowHtml(URL); 
				// select the entry in list
				selectEntryInList(id);
			});
			if(id=="") {
				arrMarker.push(marker);
			} else {
				arrMarker[id] = marker;
			}
			map.addOverlay(marker);
			if(showBubble) {
				setMapCenterZoom(marker.getPoint(),zoomLevel);
				marker.openInfoWindowHtml(URL);
			}

		}
	}
	);
}



function showMap(option) {
	MM_swapImage('MapHybrid','','img/nav_buttons/map_hybrid.png',1);
	MM_swapImage('MapNormal','','img/nav_buttons/map_normal.png',1);
	MM_swapImage('MapSatellite','','img/nav_buttons/map_satellite.png',1);
	if(option=='N') {
		map.setMapType(G_NORMAL_MAP);
		MM_swapImage('MapNormal','','img/nav_buttons/map_normal_sel.png',1);
	} else if(option=='H') {
		map.setMapType(G_HYBRID_MAP);
		MM_swapImage('MapHybrid','','img/nav_buttons/map_hybrid_sel.png',1);
	} else if(option=='S') {
		map.setMapType(G_SATELLITE_MAP);
		MM_swapImage('MapSatellite','','img/nav_buttons/map_satellite_sel.png',1);
	}
}


function querySearch(f) {
	var kdnr = document.getElementById("kdnr").value;
	var suchoption = document.getElementById("suchOption").value;
	var suchbegriff_st = (f.suchbegriff.value);
	var radSuchoption = "wort";
	if(document.getElementById("radSuchoption").checked) {
		radSuchoption = "strasse";
	}
	if(document.getElementById("radSuchoption").checked && f.suchbegriff.value=="") {
		alert("Bitte geben Sie einen Straßennamen ein!");
		return false;

	} else if(document.getElementById("radSuchoption2").checked && f.suchbegriff.value=="") {
		alert("Bitte geben Sie einen Suchbegriff ein!");
		return false;

	} else {
		if(f.suchbegriff.value.search(/,/)==-1 && document.getElementById("radSuchoption").checked) {
			alert("Geben Sie den Suchbegriff bitte in folgendem Format ein:\nStraßenname Hausnummer, Ort");
			return false;
		}
		if(f.suchbegriff.value.length==11) {
			if(f.suchbegriff.value.substr(5,6)=="e, Ort") {
				alert("Bitte geben Sie einen Straßennamen ein!");
				return false;
			}
		}
	}
	hideOtherTools();
	wasShownSearchResults = true;
	suchbegriff_st = encodeURIComponent(suchbegriff_st);
	var wait = $("#query_search_results").html("<center>Suche , bitte warten...<br><br><img src='img/ajax_loader.gif'><br><br></center>").load(f.action + "?kdnr=" + kdnr + "&suchoption=" + suchoption + "&radSuchoption=" + radSuchoption + "&" + $.param({close: 1, suche: suchbegriff_st})).showSlow();
}


function sucheUmkreis() {
	var rubrik = document.getElementById("selUmkreisRubrik").value;
	var umkreis = document.getElementById("selUmkreisMeter").value
	var kdnr = document.getElementById("kdnr").value;
	$("#DivIframeSuchergebnis").html("<center>Lade Ergebnis Umkreissuche...<br><br><img src='img/ajax_loader.gif'><br><br></center>").load("query_sucheUmkreis.php?kdnr=" + kdnr + "&rubrik=" + rubrik + "&umkreis=" + umkreis + "&x=" + markerSuche[0].getPoint().x + "&y=" + markerSuche[0].getPoint().y).showSlow();
}

function closeClearSearchResult() {
	map.clearOverlays();
	for(var i=0;i<markerSuche.length;i++) {
		map.addOverlay(markerSuche[i]);
	}
	markerSucheUmkreis=new Array();
	umKreis1=null;
	umKreis2=null;
	wasShownSearchResults=false;
	$('#query_search_results').hideSlow();
}

function showSuchergebnisse() {
	$("#sucheInResults").showSlow();
}



function checkMarker(suche,option) {
	if(markerSuche.length==0 && option=="strasse") {
		alert("Es wurde keine Straße gefunden:\n" + suche);
		$("#query_search_results").hideSlow();

	} else {
		if(option=="strasse") map.setCenter(markerSuche[0].getPoint(),map.getZoom());
		var strasse = suche;
		var arrStrasse = strasse.split(",");
		var kdnr = document.getElementById("kdnr").value;
		arrStrasse = arrStrasse[0].split(" ");
		$("#sucheInResults").html("").load("query_suche.php?kdnr=" + kdnr + "&iframe=true&suche=" + encodeURIComponent(arrStrasse[0]));
	}
}



function removeEvents() {
	GEvent.clearListeners(map,  'click');
}

function showHideRouting() {
	if(document.getElementById('routing').style.display=='none') {
		$("#routing").toggle(400);
		MM_swapImage('imgRouting','','img/nav_buttons/routing_sel.png',1);
	} else {
		$("#routing").toggle(400);
		map.clearOverlays();
		MM_swapImage('imgRouting','','img/nav_buttons/routing.png',1);	
	}
}

function setRoutingOption(option) {
	if(option=="address") {
		document.getElementById("routingAddress").style.display="block"
			document.getElementById("routingPoints").style.display="none";
		map.clearOverlays();
		GEvent.removeListener(routingEvent1);
	} else {
		document.getElementById("routingPoints").style.display="block";
		document.getElementById("routingAddress").style.display="none"
			removeEvents();
		routingEvent1 = GEvent.addListener(map, "click", onMapClick);
		reset_map();
	}
	document.getElementById("viewDirections").style.display="none";
}

function calculateRoute(fromAddress, toAddress) {
	// init google directions
	var locale = "de";
	if(gdir==null) {
		gdir = new GDirections(map, document.getElementById("viewDirections"));
		GEvent.addListener(gdir, "error", handleRouteErrors);
	}
	gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale } );
	document.getElementById("viewDirections").style.display="block";
}
function handleRouteErrors() {
	alert("Es ist ein Fehler aufgetreten.\nBitte pr&uuml;fen Sie die Angaben und erg&auml;zen Sie die Ortsangaben um Postleitzahlen.");
}
function calculateRouteFromPoints() {
	if(routingPoints.length<2) {
		alert("Bitte wählen Sie mindestens zwei Punkte auf der Karte!");
	} else {
		var locale = "de";
		var arrayABC = new Array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q');
		var toAddress = "";
		for(var i=1;i<routingPoints.length;i++) {
			toAddress += " to:" + arrayABC[i] + " @" + routingPoints[i].getPoint().lat() + ", " + routingPoints[i].getPoint().lng();
		}
		if(gdir==null) {
			gdir = new GDirections(map, document.getElementById("viewDirections"));
			GEvent.addListener(gdir, "error", handleRouteErrors);
		}
		var route = "from:A @" + routingPoints[0].getPoint().lat() + ", " + routingPoints[0].getPoint().lng() + toAddress;
		gdir.load(route, { "locale": locale } );
		document.getElementById("viewDirections").style.display="block";
		for(var i=0;i<routingPoints.length;i++) {
			routingPoints[i].remove();
		}
		routingPoints = new Array();
	}
}



function hideAreaDiv() {
	document.getElementById('area2').style.display='none';
}

function showHidemeasureArea() {
	timerlen = 1;
	slideAniLen = 600;
	reset_map();
	if(document.getElementById('area2').style.display=='none') {
		removeEvents();
		document.getElementById('area2').style.display='block';
		slidedown("area");
		measureAreaEvent1 = GEvent.addListener(map,'click',MapClick);
		MM_swapImage('imgMeasure','','img/nav_buttons/measure_sel.png',1);
	} else {
		ClearAllPoints();
		map.clearOverlays();
		slideup('area');
		window.setTimeout("hideAreaDiv()",slideAniLen);
		GEvent.removeListener(measureAreaEvent1);
		removeEvents();
		MM_swapImage('imgMeasure','','img/nav_buttons/measure.png',1);	
	}
}

function measureArea() {
	map.clearOverlays();
	ClearAllPoints();
	$("#area_text").html('Bitte beschreiben Sie eine Fl&auml;che mit mindestens drei Punkten <u>im Uhrzeigersinn</u>.');
	removeEvents();
	measureAreaEvent1 = GEvent.addListener(map,'click',MapClick);
}

function measureDistance() {
	map.clearOverlays();
	$("#area_text").html('W&auml;len Sie mindestens zwei Punkte auf der Karte.');
	removeEvents();
	lineDistance();
}


function hideMeetingDiv() {
	document.getElementById('meetingDiv2').style.display='none';
}

function selectMeetingPoint() {
	if(document.getElementById('meetingDiv2').style.display=='none') {
		removeEvents();
		document.getElementById('meetingDiv2').style.display='block';
		slidedown("meetingDivTip");
		meetingPointEvent = GEvent.addListener(map,'click',setMeetingPoint);
		MM_swapImage('imgMeeting','','img/nav/meeting_sel.png',1);
	} else {
		slideup('meetingDivTip');
		slideup('meetingDiv');
		window.setTimeout("hideMeetingDiv()",slideAniLen);
		GEvent.removeListener(meetingPointEvent);
		if(meetingPointMarker!=null) map.removeOverlay(meetingPointMarker);
		MM_swapImage('imgMeeting','','img/nav/meeting.png',1);
	}			
}

function setMeetingPoint(marker,point) {
	if(point) {
		if(document.getElementById('meetingDiv').style.display=='none') {
			slidedown("meetingDiv");
			slideup('meetingDivTip');						
		}
		meetingPoint = point;
		if(meetingPointMarker) {
			map.removeOverlay(meetingPointMarker);
			meetingPointMarker = null;
		}
		meetingIcon = new GIcon(baseIcon, "img/icons/meeting.png", null, null); 
		meetingIcon.iconSize = new GSize(24, 25);
		meetingIcon.shadowSize = new GSize(24, 25);
		meetingIcon.iconAnchor = new GPoint(9, 34);
		meetingPointMarker = new GMarker(point,{draggable : true,icon : meetingIcon});
		map.addOverlay(meetingPointMarker);
	}
}

function encodeUrl(text) {
	text = text.replace(/%/g,"%25");
	text = text.replace(/Ä/g,"%C4");
	text = text.replace(/ä/g,"%E4");
	text = text.replace(/Ö/g,"%D6");
	text = text.replace(/ö/g,"%F6");
	text = text.replace(/Ü/g,"%DC");
	text = text.replace(/ü/g,"%FC");
	text = text.replace(/ß/g,"%DF");
	text = text.replace(/!/g,"%21");
	text = text.replace(/#/g,"%23");
	text = text.replace(/\*/g,"%2A");
	text = text.replace(/\//g,"%2F");
			//text = text.replace(//g,"%3C");
			text = text.replace(/>/g,"%3E");
	text = text.replace(/\?/g,"%3F");
	return text;
}

function sendMeetingPoint() {
	if(meetingPoint) {
		var kdnr = document.getElementById("kdnr").value;
		var meetRecipent = document.getElementById("meetRecipent").value;
		var meetText = document.getElementById("meetText").value;
		meetText = encodeUrl(meetText);
		meetText = (meetText);
		var url = "mailto:" + meetRecipent + "?subject=GeoMapper Treffpunkt&body=Ihnen wurde ein GeoMapper Treffpunkt geschickt:%0A%0Ahttp://geomapper.kdo.de/" + kdnr + "/?kdnr=" + kdnr + "%26lng=" + meetingPoint.x + "%26lat=" + meetingPoint.y + "%26option=meet%0A%0AFolgende Nachricht wurde eingegeben:%0A----------------------------------%0A"+meetText;
		parent.location.href= url;
		selectMeetingPoint();

	} else {
		alert("Bitte markieren Sie zunächst den Treffpunkt auf der Karte!");
	}
}

function showHelp() {
	var subject = "";


	// load and show Help
	$("#geo_help").html('<center>Lade Hilfe</center>').load("help.php?subject="+subject).showSlow();
}

function hideHelp() {
	$("#geo_help").hideSlow();
}

function printMap() {
	var bPrint = true;
	if(map.getCurrentMapType().getName()!="Karte") {
		if(confirm("Ein Ausdruck ist in der Hybrid- und Sattelitenansicht leider nicht möglich\nMöchten Sie in die Straßenansicht wechseln?")) {
			showMap('N');
		} else {
			bPrint = false;
		}
	}
	if(bPrint) {
		var point = map.getCenter();
		var zoom = map.getZoom();
		if(zoom==14) offset=0.005;
		if(zoom==13) offset=0.010;
		if(zoom==12) offset=0.010;
		if(zoom==11) offset=0.018;
		if(zoom==10) offset=0.040;
		if(zoom==9) offset=0.100;
		if(zoom==8) offset=0.200;
		if(zoom==7) offset=0.430;
		if(zoom==6) offset=0.810;
		map.setCenter(new GLatLng((point.y-(offset)), (point.x+(offset/2))),zoom);
		window.setTimeout("print()", 1000);
	}
}
