var geocoder = new GClientGeocoder();
var map;
var theraps;
var theraps2google = new Array();
var googlestarted = 0;
var adminedit = 0;
var customeredit = 0;
var found = 0;
var notfound = 0;
var notfoundaddress = '<p style="font-size:8pt;">';
theraps = new Object();
//###############
function set_therapeut_click() {
	$(".therapeut").click(function(){
  id = $(this).attr('thisid');
  show_th(id)
	});
}

//###############
function load() {
	map = new GMap2(document.getElementById("map"));
  if (GBrowserIsCompatible()) {
    map.setCenter(new GLatLng(mycenter[0] , mycenter[1]), mycenter[2]);
		map.addControl(new GLargeMapControl());
		l=document.location + '';
		if(l.indexOf('eingabe') ==-1) load_data_into_map();
		GEvent.addListener(map, "moveend", function() {
			if(document.nameform.name.value=='') {
				load_data_into_map();
			}
		});
  }
}
//###############################
function load_data_into_map() {
	bounds = map.getBounds();
	xy = new Object();
	xy[0] = bounds.getSouthWest().lat();
	xy[1] = bounds.getSouthWest().lng();
	xy[2] = bounds.getNorthEast().lat();
	xy[3] = bounds.getNorthEast().lng();
	xy['name'] = document.nameform.name.value;
	xy['adminedit'] = adminedit;
	xy['therapid'] = therapid;
	therapid = 0;
	ajaxurl='__therapeuten.html';
	$.post(ajaxurl, xy, null, 'script');				
}
function showAddress(address,html) {
  geocoder.getLatLng(address, function(point) {
//console.log(point);
      if (!point) {
        alert(address + " not found");
      } 
      else {
//        map.setCenter(point, 6);
        var marker = new GMarker(point);
  			var html = '<div style="font-family:arial; font-size:9pt">' + html + '</DIV>';
  			GEvent.addListener(marker, "click", function() {
    			map.openInfoWindowHtml(point, html);
  			});
        map.addOverlay(marker);
      }
    }
  );
}

function getAddressInterval() {
	t = theraps2google.shift();
	getAddress(t);
	if(theraps2google.length >0) {
		window.setTimeout('getAddressInterval()', 1000);
	}
}

function getAddress(therap) {
  geocoder.getLatLng(therap['address'], function(point) {
		if (!point) {
			geocoder.getLocations(therap['address'], function (result) {
//console.log('point NOK');
				if (result.Status.code == G_GEO_SUCCESS) {
					var p = result.Placemark[0].Point.coordinates;
		      ajaxdata = {id:therap['id'], x:p[0], y:p[1]};
		      point = ajaxdata;
//console.log('x');
//console.log(ajaxdata);
//console.log(point);
		      theraps[therap['id']]['Lat'] = ajaxdata.y;
		      theraps[therap['id']]['Long'] = ajaxdata.x; 
		      showpoint(theraps[therap['id']]);
		    } 
		    else { 
	        ajaxdata = {id:therap['id'], x:-1, y:-1};
	        notfoundaddress += '<br>' + therap['address'];
		    }
	      par = new Object();
	      par.point = point;
	      par.id = therap['id'];
	      ajaxwrite(par);
		  });
		}
		else {
//console.log(point);
//        map.setCenter(point, 6);
        ajaxdata = {id:therap['id'], x:point.x, y:point.y};
        theraps[therap['id']]['Lat'] = point.y;
        theraps[therap['id']]['Long'] = point.x; 
        showpoint(theraps[therap['id']]);
      }
      par = new Object();
      par.point = point;
      par.id = therap['id'];
      ajaxwrite(par);
      if(typeof(submitbutton_default)!='undefined') $('#submitbutton').html(submitbutton_default);
    }
  );
}

function showresult() {
	if(customeredit ==1) {
		if(found==1) add = '<b>Adresse gefunden</b><br><a href="javascript:window.close()">Fenster schlie&szlig;en</a>';
		else add = "<span style='color:red; font-weight:bold;'>Adresse NICHT gefunden</span><br><a href='javascript:window.close()'>Adresse &auml;ndern</a>";
		$('.addressfound').html(add);
	}
	else {
		$('.alltherapeut').html('Offen: ' + theraps2google.length + '<br>gefunden: ' + found + '<br>nicht gefunden: ' + notfound + notfoundaddress);
	}
}

function showpoint(therap) {
//console.log(therap);
	if(therap['id']>0 && therap['Lat']<0.001 && therap['Long']<0.001) {
		if(adminedit==1 || customeredit==1) {
			theraps2google[theraps2google.length] = therap;
			showresult();
			if(googlestarted == 0) {
				window.setTimeout('getAddressInterval()', 1000);
				googlestarted = 1;
			}
		}
		return;
	}
	point = new GLatLng(therap['Lat'], therap['Long'], true);
  var marker = new GMarker(point);
  var html = '<div style="font-family:arial; font-size:9pt">' + therap['html'] + '</DIV>';
  GEvent.addListener(marker, "click", function() {
    p = new GLatLng(therap['Lat'], therap['Long'], true);
    map.openInfoWindowHtml(p, html);
  });
  map.addOverlay(marker);
}

function show_th(id) {
  if(theraps[id]['Lat']>=-1 && theraps[id]['Lat']<=0 && theraps[id]['Long']>=-1 && theraps[id]['Long']<=0) {
  	alert('Adresse wird nicht erkannt, kann nicht auf Karte angezeigt werden.');
  }
  else {
	  var zoom = 10;
	  if(theraps[id]['plz'].substr(0,3)=='A-1') zoom = 12; // Wien
	  if(theraps[id]['plz'].substr(0,4)=='A-80') zoom = 11; // Graz
	  if(theraps[id]['plz'].substr(0,4)=='A-40') zoom = 11; // Linz
	  if(theraps[id]['plz'].substr(0,4)=='A-50') zoom = 11; // Salzburg
	  p = new GLatLng(theraps[id]['Lat'], theraps[id]['Long'], true);
	  map.setCenter(p, zoom);
	  map.openInfoWindowHtml(p, theraps[id]['html']);
	}
}

$(function() {
	load();
	set_therapeut_click();
});

$(window).unload( function(e) {
	GUnload();
}); 
