var poiService = "http://services.gsk-onkologie.de/gsk-psychoonkologen";
if (window.location.href.indexOf('xma') > 0) {
	poiService = "http://gsk-onkologie.dev.xmachina.de/gsk-psychoonkologen";
} 

new PoiFinder();

function PoiFinder() {
	var map;
	var currentLocationLatLng;
	var requestId = 0;
	
	var pageFirstResult = 0;
	var pageMaxResult = 10;
	
	var therapyTypes = new Object();
		
	therapyTypes = { 
		entspannungstherapie : { 
			label : "Entspannungstherapie",
			color : "blue"
		},
		gespraechstherapie : { 
			label : "Gespr&auml;chstherapie",
			color : "green"
		},
		gestaltungstherapie : { 
			label : "Kreative/Gestaltungstherapie",
			color : "yellow"
		},
		verhaltenstherapie : { 
			label : "Verhaltenstherapie",
			color : "grey"
		},
		sonstige : { 
			label : "Sonstige",
			color : "orange"
		}			
	};
	
	
	// Event observer
	Event.observe(window, 'load', init); 
	
	/**
	 * Initialization. Called at onLoad
	 */
	function init() {
		doLog("Initializing POI Finder.");
		
		if (!GBrowserIsCompatible()) {
			alert("Ihr Browser ist nicht mit Google Maps kompatibel.");
			return;
		}
	    
		// Create map
		map = new GMap2(document.getElementById("poiMapPanel"));
	    map.setCenter(new GLatLng(50.974401, 10.325228), 6);
	    map.setUIToDefault();
	    		
	    // Search panel
	    Event.observe("frmSearchPanel", "submit", onSubmitSearchPanel);
		
	}
	
	function onSubmitSearchPanel(event) {
		event.stop();
		doLog("Search panel submitted.");
		
		var location = $F("location");
		if (location == null || location == "") {
			alert("Bitte geben Sie einen Ort ein.");
			return;
		}
		
		location+= ", Deutschland";
		doLog("Get geo pos for " + location);
		geocoder = new GClientGeocoder();
		geocoder.getLatLng(location, function(latLng) {
			if (!latLng) {
				doLog("Address not found for " + location);
	            alert("Adresse nicht gefunden.");
	        } else {
	        	doLog("Found lat lng: " + latLng);
	        	currentLocationLatLng = latLng;
	        	clearResults();
	        	loadPois();
	        }
		});
	}
	
	function clearResults() {
		$$("div.poiPanel").each(function(poiPanel){
			Element.remove(poiPanel);
		});
		
		map.clearOverlays();
		
		pageFirstResult = 0;
	}
	
	function loadPois() {
		doLog("Load POIs...");
		var callback = "callback" + requestId++;

		// Service URL
		var url = poiService + "/pois.json?callback=" + callback + "&lat=" + 
			currentLocationLatLng.lat() + "&lng=" + currentLocationLatLng.lng() + 
			"&pageFirstResult=" + pageFirstResult + "&pageMaxResult=" + pageMaxResult;
		doLog("Query URL: " + url);
		
		// Create a script element.
		var script = document.createElement("script");
		script.setAttribute("src", url);
		script.setAttribute("type", "text/javascript");
	
		window[callback] = function(jsonObj) {
			handlePoiResponse(jsonObj);
			window[callback + "done"] = true;
		}

		setTimeout(function() {
			if (!window[callback + "done"]) {
				handlePoiResponse(null);
			}
			try {
				delete window[callback];
				delete window[callback + "done"];
			} catch(e) {
				doLog("Could not delete callback");
			}
		}, 2000);

		document.body.appendChild(script);
	}
	
	function handlePoiResponse(poiResponse) {
		doLog("Handle POI response. ");
		
		if (poiResponse == null) {
			doLog("POI response is NULL. ");
			alert("Der Service liefert keine Daten.");
			return;
		}
		
		doLog("Total POI count: " + poiResponse.totalCount);
		updateResults(poiResponse);
		
		createMoreResultsPanel();
	}
	
	function createMoreResultsPanel() {
		if ($("moreResultsPanel") != null)
			Element.remove("moreResultsPanel");
		
		var panel = new Element('div');
		panel.addClassName("moreResultsPanel");
		panel.id = "moreResultsPanel";
		panel.innerHTML = "mehr &#187;";
		$("poiResultPanel").appendChild(panel);
		
		Event.observe(panel, "click", function() {
			pageFirstResult+= pageMaxResult;
			doLog("Paging to " + pageFirstResult);
			loadPois();
		});
	}
	
	function updateResults(poiResponse) {
		lat1 = 1000; lat2 = 0; lng1 = 1000; lng2 = 0;
		
		for (var i=0; i<poiResponse.pois.length; i++) {
			doLog("Progressing POI " + poiResponse.pois[i].id);
			
			if (poiResponse.pois[i].lat < lat1) lat1 = poiResponse.pois[i].lat;
		    if (poiResponse.pois[i].lat > lat2) lat2 = poiResponse.pois[i].lat;
		    if (poiResponse.pois[i].lng < lng1) lng1 = poiResponse.pois[i].lng;
		    if (poiResponse.pois[i].lng > lng2) lng2 = poiResponse.pois[i].lng;
		   		    
			// Add marker
		    map.addOverlay(createMarker(poiResponse.pois[i]));
		    
		    // Add poi panel
		    createPoiPanel(poiResponse.pois[i]);
		}
		
		// Place Map over the area
		var bounds = new GLatLngBounds(new GLatLng(lat1, lng1), new GLatLng(lat2, lng2));
		doLog("New bounds: " + bounds);
		var zoom = map.getBoundsZoomLevel(bounds);
		doLog("New zoom: " + zoom);
		map.setCenter(bounds.getCenter());
		map.setZoom(zoom);
	}
	
	// Create a new marker for the given POI
	function createMarker(poi) {
	      var marker = new GMarker(new GLatLng(poi.lat, poi.lng));
	      marker.poi = poi;
	      GEvent.addListener(marker,"click", function() {
	    	  $("poiPanel" + poi.id).scrollIntoView();
	    	  onSelectPoi(poi)
	      });
	      return marker;
	}
	
	function createPoiPanel(poi) {
		var panel = new Element('div');
		panel.addClassName('poiPanel');
		panel.addClassName('clerasil');
		panel.id = "poiPanel" + poi.id;
		panel.innerHTML = renderPoiPanel(poi);
		$("poiResultPanel").appendChild(panel);
		
		Event.observe(panel, "click", function() {
			onSelectPoi(poi);
		});
	}
	
	function onSelectPoi(poi) {
		doLog("Select POI " + poi.id);
		
		// Deselect
		$$("div.poiPanel").each(function(poiPanel){
			poiPanel.removeClassName("poiSelected");
		});
		
		// Select
		$("poiPanel" + poi.id).addClassName("poiSelected");
		map.openInfoWindowHtml(new GLatLng(poi.lat, poi.lng), renderPoiInfoWindow(poi));
		
		location.href =(location.href.indexOf("#map") == -1) ? location.href + "#map" : location.href; 
  	  	
	}


	// Renders the HTML for the google Map Bubble.
	function renderMapBubble(poi) {
		
		// Combines the name with title and firstname
		var name = (poi.title != "" && poi.title != null) ? poi.title + " " : "";
		name += ( poi.firstName != "" && poi.firstName != null) ? poi.firstName + " " +  poi.name : " " + poi.name; 	
		
		var html = '<div class="poiPanel"><div class="name">' + name + "</div>\n";
		html+= poi.street + "<br />";
		html+= poi.zipCode + " " + poi.city + "<br />";
		html+= poi.country + "<br />";
		html+= "<a href='mailto:" + poi.eMail + "'>" + poi.eMail + "</a><br /></div>";
		return html;	
	}
		
	
	// Renders the HTML for the Therapytype section of the POI panel
	function renderTherapyTypes(key, secondCell) {
		
		var cssClass = (secondCell % 2 == 1) ? "col last" : "col";
		
		var html = '	<div class="' + cssClass + '">';
		
		html += '		<span class="' + therapyTypes[key]["color"] + '">' +	therapyTypes[key]["label"] + "</span>";
																
		html += "	</div>\n";	
		
		if (secondCell % 2 == 1) {
			
			html += "</div>\n";
			html += '<div class="row clerasil">' + "\n";
			
		}
		
		return html;
	}
	
	
	
	// Renders the HTML for a single POI panel.
	function renderPoiPanel(poi) {
		
		// Combines the name with title and firstname
		var name = (poi.title != "" && poi.title != null) ? poi.title + " " : "";
		name += ( poi.firstName != "" && poi.firstName != null) ? poi.firstName + " " +  poi.name : " " + poi.name; 	
		
		var html = '<div class="name">' + name + "</div>\n";
		
		// Prepares the address
		html += '<div id="address" class="row clerasil">' + "\n";				
		html += '	<div class="col">' + "\n";
		html += '		<div class="padding_10">' + "\n";
		html += poi.street + ", " + poi.zipCode + " " + poi.city + "<br/>\n";
		
		html += '			<span class="line"><span class="label">Telefon:</span>' + "\n";				
		html += (poi.phone != "" && poi.phone != null) ? poi.phone + "</span>\n" : "-</span>\n";
		
		html += '			<span class="line"><span class="label">Telefax:</span>';			
		html += (poi.fax != "" && poi.fax != null) ? poi.fax + "</span>\n" : "-</span>\n";	
								
		html += "		</div>\n";
		html += "	</div>\n";
						
		html += '	<div class="col last">';
		html += ' 		<span class="line"><span class="label">E-Mail:</span>' + "\n";	
		html += (poi.eMail != "" && poi.eMail != null) ? '<a href="mailto:' + poi.eMail + '" target="_blank">' + poi.eMail + "</a></span>\n" : "-</span>\n";	
		
		html += ' 		<span class="line"><span class="label">Internet:</span>' + "\n";	
		html += (poi.homepage != "" && poi.homepage != null) ? '<a href="http://' + poi.homepage + '" target="_blank">' + poi.homepage + "</a></span>\n" : "-</span>\n";	
		
		html += "	</div>\n";
		html += "</div>\n";
		
		// Prepares the institution type		
		html += '<div id="institution" class="section">';
		html += '	<span class="title">Einrichtung: </span>';
						
		html += '	<div class="row institutionName">';
		
		var institutionType = ""; 
		if (poi.institute.indexOf("praxis",0) != -1 || poi.institute.indexOf("Praxis",0) != -1) 	institutionType = "praxis"; 
		if (poi.institute.indexOf("klinik",0) != -1 || poi.institute.indexOf("Klinik",0) != -1) 	institutionType = "klinikum";
		if (poi.institute.indexOf("reha",0) != -1 || poi.institute.indexOf("Reha",0) != -1)   		institutionType = "reha";
		if (poi.institute.indexOf("beratung",0) != -1 || poi.institute.indexOf("Beratung",0) != -1) institutionType = "beratung";
		
		if (institutionType != "") {
			html += '		<span class="types">';
			html += '			<img src="ressource/images/types_' + institutionType + '.gif" />';
			html += '		</span>';
		}

		html += '		<span>' + poi.institute + '</span>';
		html += "	</div>\n";
						
		html += "</div>";		
		
		// Prepares the therapy types
		html += '<div id="therapyTypes" class="section">';
		html += '	<span class="title">Therapieform: </span>';			
		html += '	<div class="row clerasil">'
		
		var counter = 0;
		if (poi.entspannungstherapie == true) html += renderTherapyTypes("entspannungstherapie", counter++);
		if (poi.gespraechstherapie == true)   html += renderTherapyTypes("gespraechstherapie", counter++);
		if (poi.gestaltungstherapie == true)  html += renderTherapyTypes("gestaltungstherapie", counter++);
		if (poi.verhaltenstherapie == true)   html += renderTherapyTypes("verhaltenstherapie", counter++);
		if (poi.sonstige != null && poi.sonstige != "") { 
			
			therapyTypes["sonstige"]["label"] = "Sonstige: " + poi.sonstige;
			
			if (poi.therapyForm != null && poi.therapyForm != "") {
				therapyTypes["sonstige"]["label"] += "<br/>" + poi.therapyForm;
			}
			
			html += renderTherapyTypes("sonstige", counter++);
		}
		
		html += "	</div>\n";	
		html += "</div>\n";			
					
		// Prepares  further attributes
		html += '<div id="attributes">';
		html += '	<div class="row clerasil">';
		
		html += '		<div class="col">';
		html += '			<div class="padding_10">';			
		html += '				<div class="section">';
		html += '					<span class="title">Approbation als Psychotherapeut: </span><br/>';
		
		html += (poi.approbation != null && poi.approbation != "") ? poi.approbation : "Nein";
										
		html += "				</div>\n";	
		html += "			</div>\n";	
		html += "		</div>\n";	
							
		html += '		<div class="col last">';
		html += '			<div class="section">';
		html += '				<span class="title">Zertifikat: </span><br/>';
		html += (poi.certificate != null && poi.certificate != "") ? poi.certificate : "Nein";
		html += "			</div>\n";	
		html += "		</div>\n";	
		
		html += "	</div>\n";	
		html += "</div>\n";	
										
					
		
		return html;
		
	}
	
	// Renders the HTML for the map's info window
	function renderPoiInfoWindow(poi) {
		// TODO: Place your custom info window render code here
		// By default we render the same content as within the POI panel
		
		//return renderPoiPanel(poi);      ZUVIEL INFO FÜR DIE MAP
		return renderMapBubble(poi);
	}
	
}



function doLog(message) {
	try {
		top.console.log(message);
	} catch (e) {
	}
}
