
var default_lat = 50.4234314;
var default_lng = 10.9074957;
var default_radius = 50;
var zoom_level = 6;
var map_width = "100%";
var map_height = "450px";
var special_text = "Drössiger Gold Händler";
var units = "km";
var limit = "0";
var plugin_url = "http://www.droessiger.de/wp-content/plugins/simplemap/";
var autozoom = 6;
var default_domain = ".de";
var address_format = "postalcode town";
var visit_website_text = "Website anzeigen";
var get_directions_text = "Route berechnen";
var location_tab_text = "Startpunkt";
var description_tab_text = "Beschreibung";
var phone_text = "Tel";
var fax_text = "Fax";
var tags_text = "Schlagworte";
var noresults_text = "Keine Ergebnisse gefunden.";

var map;
var geocoder;

function codeAddress() {
	geocoder = new GClientGeocoder();
	var d_address = document.getElementById("default_address").value;
		 geocoder.getLatLng(d_address, function(latlng) {
			document.getElementById("default_lat").value = latlng.lat();
			document.getElementById("default_lng").value = latlng.lng();
		 });
}

function codeNewAddress() {
	if (document.getElementById("store_lat").value != '' && document.getElementById("store_lng").value != '') {
		document.new_location_form.submit();
	}
	else {
		geocoder = new GClientGeocoder();
		var address = '';
		var street = document.getElementById("store_address").value;
		var city = document.getElementById("store_city").value;
		var state = document.getElementById("store_state").value;
		var country = document.getElementById("store_country").value;
		
		if (street) { address += street + ', '; }
		if (city) { address += city + ', '; }
		if (state) { address += state + ', '; }
		address += country;
	
		 geocoder.getLatLng(address, function(latlng) {
			document.getElementById("store_lat").value = latlng.lat();
			document.getElementById("store_lng").value = latlng.lng();
			document.new_location_form.submit();
		 });
	}
}

function codeChangedAddress() {
	geocoder = new GClientGeocoder();
	var address = '';
	var street = document.getElementById("store_address").value;
	var city = document.getElementById("store_city").value;
	var state = document.getElementById("store_state").value;
	var country = document.getElementById("store_country").value;
	
	if (street) { address += street + ', '; }
	if (city) { address += city + ', '; }
	if (state) { address += state + ', '; }
	address += country;

	geocoder.getLatLng(address, function(latlng) {
		document.getElementById("store_lat").value = latlng.lat();
		document.getElementById("store_lng").value = latlng.lng();
	});
}

function searchLocations(categories) {
 var address = document.getElementById('addressInput').value;
 address = address.replace(/&/gi, " ");
 geocoder.getLatLng(address, function(latlng) {
   if (!latlng) {
     latlng = new GLatLng(150,100);
     searchLocationsNear(latlng, address, "search", "unlock", categories);
   } else {
     searchLocationsNear(latlng, address, "search", "unlock", categories);
   }
 });
}

function searchLocationsNear(center, homeAddress, source, mapLock, categories) {
	var selectedCountry = document.getElementById('selectedCountry').value;
	if (selectedCountry == '') {
		selectedCountry = 'DE';
	}
	var catFilter = document.getElementById('catFilter').value;
	if (document.getElementById('radiusSelect')) {
		if (units == 'mi') {
		  	var radius = parseInt(document.getElementById('radiusSelect').value);
		}
		else if (units == 'km') {
		  	var radius = parseInt(document.getElementById('radiusSelect').value) / 1.609344;
		}
	}
	else {
		if (units == 'mi') {
		  	var radius = parseInt(default_radius);
		}
		else if (units == 'km') {
		  	var radius = parseInt(default_radius) / 1.609344;
		}
	}
 
	if (source == 'auto_all') {
		var searchUrl = plugin_url + 'actions/create-xml.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=infinite&namequery=' + homeAddress + '&limit=0&categories=' + categories + '&selectedCountry=' + selectedCountry + '&catFilter=' + catFilter;
	}
	else {
		var searchUrl = plugin_url + 'actions/create-xml.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius + '&namequery=' + homeAddress + '&limit=' + limit + '&categories=' + categories + '&selectedCountry=' + selectedCountry + '&catFilter=' + catFilter;
	}
	GDownloadUrl(searchUrl, function(data) {
		var xml = GXml.parse(data);
		var markers = xml.documentElement.getElementsByTagName('marker');
		map.clearOverlays();
		
		var results = document.getElementById('results');
		results.innerHTML = '';
		if (markers.length == 0) {
			results.innerHTML = '<h3>' + noresults_text + '</h3>';
			map.setCenter(new GLatLng(default_lat,default_lng), zoom_level);
			return;
		}
		else {
			if (markers.length == 1) {
				results.innerHTML = 'Es wurde ' + markers.length + ' Händler gefunden.';
			}
			else {
				results.innerHTML = 'Es wurden ' + markers.length + ' Händler gefunden.';
			}
		}
		var bounds = new GLatLngBounds();
		for (var i = 0; i < markers.length; i++) {
			var name = markers[i].getAttribute('name');
			var address = markers[i].getAttribute('address');
			var address2 = markers[i].getAttribute('address2');
			var city = markers[i].getAttribute('city');
			var state = markers[i].getAttribute('state');
			var zip = markers[i].getAttribute('zip');
			var country = markers[i].getAttribute('country');
			var distance = parseFloat(markers[i].getAttribute('distance'));
			var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')), parseFloat(markers[i].getAttribute('lng')));
			var url = markers[i].getAttribute('url');
			var phone = markers[i].getAttribute('phone');
			var fax = markers[i].getAttribute('fax');
			var special = markers[i].getAttribute('special');
			var category = markers[i].getAttribute('category');
			var tags = markers[i].getAttribute('tags');
			if (markers[i].firstChild) {
				var description = markers[i].firstChild.nodeValue;
			}
			else {
				var description = '';
			}
			var marker = createMarker(point, name, address, address2, city, state, zip, country, homeAddress, url, phone, fax, special, category, tags, description);
			map.addOverlay(marker);
			var sidebarEntry = createSidebarEntry(marker, name, address, address2, city, state, zip, country, distance, homeAddress, phone, fax, url, special, category, tags, description);
			results.appendChild(sidebarEntry);
			bounds.extend(point);
		}
		if (source == "search") {
			map.setCenter(bounds.getCenter(), (map.getBoundsZoomLevel(bounds)));
			if(distance.toFixed(0)== 'NaN') {
				//alert(distance.toFixed(0));
			}
			else {
				//Set marker on startpoint 
				var startpointIcon = new GIcon();
				startpointIcon.image = plugin_url + '/images/marker-img/markers-pin/image.png';
				startpointIcon.shadow = plugin_url + '/images/marker-img/markers-pin/shadow.png';
				startpointIcon.iconSize = new GSize(24,30);
				startpointIcon.shadowSize = new GSize(39,30);
				startpointIcon.iconAnchor = new GPoint(0,30);
				startpointIcon.infoWindowAnchor = new GPoint(12,0);
				startpointIcon.printImage = plugin_url + '/images/marker-img/markers-pin/printImage.gif';
				startpointIcon.mozPrintImage = plugin_url + '/images/marker-img/markers-pin/mozPrintImage.gif';
				startpointIcon.printShadow = plugin_url + '/images/marker-img/markers-pin/printShadow.gif';
				startpointIcon.transparent = plugin_url + '/images/marker-img/markers-pin/transparent.png';
				startpointIcon.imageMap = [15,0,17,1,18,2,19,3,20,4,20,5,21,6,21,7,21,8,21,9,21,10,21,11,20,12,20,13,20,14,18,15,18,16,17,17,11,18,10,19,10,20,9,21,9,22,8,23,8,24,7,25,6,26,6,27,5,28,5,29,0,29,0,28,1,27,1,26,2,25,3,24,3,23,4,22,4,21,5,20,5,19,6,18,7,17,7,16,8,15,6,14,6,13,5,12,5,11,5,10,5,9,5,8,5,7,5,6,5,5,6,4,6,3,8,2,9,1,11,0];
				markerOptions = {icon:startpointIcon};
				var startpointMarker = new GMarker(center, markerOptions)
				map.addOverlay(startpointMarker);
				// Set up our GMarkerOptions object
				GEvent.addListener(startpointMarker, "click", function() {
					startpointMarker.openInfoWindowHtml("Suche im Umkreis von " + document.getElementById('radiusSelect').value + " " + units + " um " + homeAddress);
				});
				drawCircle(center.lat(), center.lng(), parseInt(document.getElementById('radiusSelect').value), "#ff9900", 5, 0.75, "#FFFFFF",.2);
			}
		}
		else if (mapLock == "unlock") {
			//map.setCenter(bounds.getCenter(), autozoom);
			map.setCenter(new GLatLng(default_lat,default_lng), zoom_level);
		}
		});
}
//
/**
     * Add a circle to the global variable "map". This function won't work for circles that encompass
     * the North or South Pole. Also, there is a slight distortion in the upper-left, upper-right,
     * lower-left, and lower-right sections of the circle that worsens as it gets larger and/or closer
     * to a pole.
     * @param lat Latitude in degrees
     * @param lng Longitude in degrees
     * @param radius Radius of the circle in statute miles
     * @param {String} strokeColor Color of the circle outline in HTML hex style, e.g. "#FF0000"
     * @param strokeWidth Width of the circle outline in pixels
     * @param strokeOpacity Opacity of the circle outline between 0.0 and 1.0
     * @param {String} fillColor Color of the inside of the circle in HTML hex style, e.g. "#FF0000"
     * @param fillOpacity Opacity of the inside of the circle between 0.0 and 1.0
     */
function drawCircle(lat, lng, radius, strokeColor, strokeWidth, strokeOpacity, fillColor, fillOpacity) {
      var d2r = Math.PI/180;
      var r2d = 180/Math.PI;
      var Clat = radius * 0.621371192 * 0.014483;  // Convert statute (miles) (kilometers = * 0.621371192) into degrees latitude
      var Clng = Clat/Math.cos(lat*d2r); 
      var Cpoints = []; 
      for (var i=0; i < 33; i++) { 
        var theta = Math.PI * (i/16);
        Cy = lat + (Clat * Math.sin(theta));
        Cx = lng + (Clng * Math.cos(theta));
        var P = new GLatLng(Cy, Cx);
        Cpoints.push(P);
      }
      var polygon = new GPolygon(Cpoints, strokeColor, strokeWidth, strokeOpacity, fillColor, fillOpacity);
      map.addOverlay(polygon);
      map.setCenter(polygon.getBounds().getCenter(),map.getBoundsZoomLevel(polygon.getBounds()));
}

function stringFilter(s) {
	filteredValues = "emnpxt%";     // Characters stripped out
	var i;
	var returnString = "";
	for (i = 0; i < s.length; i++) {  // Search through string and append to unfiltered values to returnString.
		var c = s.charAt(i);
		if (filteredValues.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}
function createMarker(point, name, address, address2, city, state, zip, country, homeAddress, url, phone, fax, special, category, tags, description) {
	var letteredIcon = new GIcon(G_DEFAULT_ICON);
	var showMarker= '1';
	if (category == 'Drössiger Fachhändler') {
		showMarker= '1';
	  }
	  if (category == 'Drössiger Gold Händler') {
		showMarker= '4';
	  }
	  if (category == 'Drössiger Silber Händler') {
		showMarker= '3';
	  }
	letteredIcon.image = plugin_url + '/images/btn-dr-' + showMarker + '.png';
	letteredIcon.iconSize = new GSize(30, 50);
	letteredIcon.shadowSize = new GSize(50, 30);
	letteredIcon.iconAnchor = new GPoint(15, 50);
	letteredIcon.infoWindowAnchor = new GPoint(15, 50);
	
	letteredIcon.image = plugin_url + '/images/marker-img/markers-' + showMarker + '/image.png';
	letteredIcon.shadow =  plugin_url + '/images/marker-img/markers-' + showMarker + '/shadow.png';
	letteredIcon.iconSize = new GSize(30,50);
	letteredIcon.shadowSize = new GSize(55,50);
	letteredIcon.iconAnchor = new GPoint(15,50);
	letteredIcon.infoWindowAnchor = new GPoint(15,50);
	letteredIcon.printImage =  plugin_url + '/images/marker-img/markers-' + showMarker + '/ printImage.gif';
	letteredIcon.mozPrintImage =  plugin_url + '/images/marker-img/markers-' + showMarker + '/mozPrintImage.gif';
	letteredIcon.printShadow =  plugin_url + '/images/marker-img/markers-' + showMarker + '/printShadow.gif';
	letteredIcon.transparent =  plugin_url + '/images/marker-img/markers-' + showMarker + '/transparent.png';
	letteredIcon.imageMap = [26,0,28,1,29,2,29,3,29,4,29,5,29,6,29,7,29,8,29,9,29,10,29,11,29,12,29,13,29,14,29,15,29,16,29,17,29,18,29,19,29,20,29,21,29,22,29,23,29,24,29,25,29,26,29,27,28,28,27,29,19,30,18,31,18,32,18,33,18,34,18,35,17,36,17,37,17,38,17,39,17,40,16,41,16,42,16,43,16,44,15,45,15,46,15,47,15,48,15,49,14,49,14,48,14,47,14,46,14,45,13,44,13,43,13,42,13,41,12,40,12,39,12,38,12,37,12,36,11,35,11,34,11,33,11,32,11,31,10,30,2,29,1,28,1,27,1,26,1,25,1,24,1,23,1,22,1,21,1,20,1,19,1,18,1,17,1,16,1,15,1,14,1,13,1,12,1,11,1,10,1,9,1,8,1,7,1,6,1,5,1,4,1,3,1,2,1,1,3,0];
	
	markerOptions = {icon:letteredIcon};
	var marker = new GMarker(point, markerOptions);
	
	var mapwidth = Number(stringFilter(map_width));
	var mapheight = Number(stringFilter(map_height));
	
	var maxbubblewidth = Math.round(mapwidth / 1.5);
	var maxbubbleheight = Math.round(mapheight / 2.2);
	
	var fontsize = 10;
	var lineheight = 10;
	
	var titleheight = 3 + Math.floor((name.length + category.length) * fontsize / (maxbubblewidth * 1.5));
	//var titleheight = 2;
	var addressheight = 2;
	if (address2 != '') {
		addressheight += 1;
	}
	if (phone != '' || fax != '') {
		addressheight += 1;
		if (phone != '') {
			addressheight += 1;
		}
		if (fax != '') {
			addressheight += 1;
		}
	}
	var tagsheight = 0;
	var linksheight = 2;
	var totalheight = (titleheight + addressheight + tagsheight + linksheight + 1) * fontsize;
		
	if (totalheight > maxbubbleheight) {
		totalheight = maxbubbleheight;
	}
	
	var html = '	<div class="markertext" style="height: ' + totalheight + 'px; overflow-y: auto; overflow-x: hidden;">';
	html += '		<h3 style="margin-top: 0; padding-top: 0; border-top: none;">' + name + '<br /><span class="bubble_category">' + category + '</span></h3>';
	html += '		<p>' + address;
					if (address2 != '') {
	html += '			<br />' + address2;
					}
					
					if (address_format == 'town, province postalcode') {
	html += '		<br />' + city + ', ' + state + ' ' + zip + '</p>';
					}
					else if (address_format == 'town province postalcode') {
	html += '		<br />' + city + ' ' + state + ' ' + zip + '</p>';
					}
					else if (address_format == 'town-province postalcode') {
	html += '		<br />' + city + '-' + state + ' ' + zip + '</p>';
					}
					else if (address_format == 'postalcode town-province') {
	html += '		<br />' + zip + ' ' + city + '-' + state + '</p>';
					}
					else if (address_format == 'postalcode town, province') {
	html += '		<br />' + zip + ' ' + city + ', ' + state + '</p>';
					}
					else if (address_format == 'postalcode town') {
	html += '		<br />' + zip + ' ' + city + '</p>';
					}
					else if (address_format == 'town postalcode') {
	html += '		<br />' + city + ' ' + zip + '</p>';
					}
					
					if (phone != '') {
	html += '			<p>' + phone_text + ': ' + phone;
						if (fax != '') {
	html += '				<br />' + fax_text + ': ' + fax;
						}
	html += '			</p>';
					}
					else if (fax != '') {
	html += '			<p>' + fax_text + ': ' + fax + '</p>';
					}
					/*if (tags != '') {
	html += '			<p class="bubble_tags">' + tags_text + ': ' + tags + '</p>';
					}
					var dir_address = address + ',' + city;
					if (state) { dir_address += ',' + state; }
					if (zip) { dir_address += ',' + zip; }
					if (country) { dir_address += ',' + country; }
	html += '		<p class="bubble_links"><a href="http://google' + default_domain + '/maps?q=' + homeAddress + ' to ' + dir_address + '" target="_blank">' + get_directions_text + '</a>';*/
					if (url != '') {
	html += '			<a href="' + url + '" title="' + name + '" target="_blank">' + visit_website_text + '</a>';
					}
	html += '		</p>';
	html += '	</div>';
	
	if (description != '') {
		var numlines = Math.ceil(description.length / 40);
		var newlines = description.split('<br />').length - 1;
		var totalheight2 = 0;
		
		if (description.indexOf('<img') == -1) {
			totalheight2 = (numlines + newlines + 1) * fontsize;
		}
		else {
			var numberindex = description.indexOf('height=') + 8;
			var numberend = description.indexOf('"', numberindex);
			var imageheight = Number(description.substring(numberindex, numberend));
			
			totalheight2 = ((numlines + newlines - 2) * fontsize) + imageheight;
		}
		
		if (totalheight2 > maxbubbleheight) {
			totalheight2 = maxbubbleheight;
		}
		
		var html2 = '	<div class="markertext" style="height: ' + totalheight2 + 'px; overflow-y: auto; overflow-x: hidden;">' + description + '</div>';
		
		GEvent.addListener(marker, 'click', function() {
			marker.openInfoWindowTabsHtml([new GInfoWindowTab(location_tab_text, html), new GInfoWindowTab(description_tab_text, html2)], {maxWidth: maxbubblewidth});
			//window.location = '#map_top';
		});
	}

	else {
		GEvent.addListener(marker, 'click', function() {
			marker.openInfoWindowHtml(html, {maxWidth: maxbubblewidth});
			//window.location = '#map_top';
		});
	}
	return marker;
}

function createSidebarEntry(marker, name, address, address2, city, state, zip, country, distance, homeAddress, phone, fax, url, special, category, tags, description) {
  var div = document.createElement('div');
  
  // Beginning of result
  var html = '<div class="result">';
  
  // Flagged special
  /*if (special == 1 && special_text != '') {
  	html += '<div class="special">' + special_text + '</div>';
  }*/
  if (category == 'Drössiger Fachhändler') {
  	html += '<div class="special1">' + category + '</div>';
  }
  if (category == 'Drössiger Gold Händler') {
  	html += '<div class="special4">' + category + '</div>';
  }
  if (category == 'Drössiger Silber Händler') {
  	html += '<div class="special3">' + category + '</div>';
  }
  // Name & distance
  html += '<div class="result_name">';
  html += '<h3 style="margin-top: 0; padding-top: 0; border-top: none;">' + name;
  if (distance.toFixed(1) != 'NaN') {
  	if (units == 'mi') {
	  	html+= ' <small>' + distance.toFixed(1) + ' miles</small>';
	}
  	else if (units == 'km') {
	  	html+= ' <small>' + (distance * 1.609344).toFixed(1) + ' km</small>';
	}
  }
  html += '</h3></div>';
  
  // Address
  html += '<div class="result_address"><address>' + address;
  if (address2 != '') {
  	html += '<br />' + address2;
  }
  
	if (address_format == 'town, province postalcode') {
		html += '<br />' + city + ', ' + state + ' ' + zip + '</address></div>';
	}
	else if (address_format == 'town province postalcode') {
		html += '<br />' + city + ' ' + state + ' ' + zip + '</address></div>';
	}
	else if (address_format == 'town-province postalcode') {
		html += '<br />' + city + '-' + state + ' ' + zip + '</address></div>';
	}
	else if (address_format == 'postalcode town-province') {
		html += '<br />' + zip + ' ' + city + '-' + state + '</address></div>';
	}
	else if (address_format == 'postalcode town, province') {
		html += '<br />' + zip + ' ' + city + ', ' + state + '</address></div>';
	}
	else if (address_format == 'postalcode town') {
	if(country == 'DE') {
		html += '<br />' + zip + ' ' + city + '</address></div>';
		} 
		else {
			html += '<br />' + zip + ' ' + city + ' (' + country + ')</address></div>';
		}
	}
	else if (address_format == 'town postalcode') {
		html += '<br />' + city + ' ' + zip + '</address></div>';
	}
  
  // Phone & fax numbers
  html += '<div class="result_phone">';
  if (phone != '') {
  	html += phone_text + ': ' + phone;
  }
  if (fax != '') {
  	html += '<br />' + fax_text + ': ' + fax;
  }
  html += '</div>';
  
  // Links section
  html += '<div class="result_links">';
  
  // Visit Website link
  html += '<div>';
  if (url != 'http://' && url != '') {
  	html += '<a href="' + url + '" title="' + name + '" target="_blank">' + visit_website_text + '</a>';
  }
  html += '</div>';
  
  // Get Directions link
  if (distance.toFixed(1) != 'NaN') {
					var dir_address = address + ',' + city;
					if (state) { dir_address += ',' + state; }
					if (zip) { dir_address += ',' + zip; }
					if (country) { dir_address += ',' + country; }
	  html += '<a href="http://google' + default_domain + '/maps?q=' + homeAddress + ',' + country + ' nach ' + dir_address + '" target="_blank">' + get_directions_text + '</a>';
  }
  html += '</div>';
  
  html += '<div style="clear: both;"></div>';
  
  // End of result
  html += '</div>';
  
  div.innerHTML = html;
  div.style.cursor = 'pointer'; 
  div.style.margin = 0;
  GEvent.addDomListener(div, 'click', function() {
    GEvent.trigger(marker, 'click');
    window.location = '#map_top';
  });
  GEvent.addDomListener(div, 'mouseover', function() {
    //div.style.backgroundColor = '#eee';
  });
  GEvent.addDomListener(div, 'mouseout', function() {
    //div.style.backgroundColor = '#fff';
  });
  return div;
}
