var markerActPos = null;
var markerActPosClick = null;
var pointMarkers = [];
var pointMarkersInfo = [];
var highlightedMarker = null;

//Ext.QuickTips.init();

document.mm.settings.qtipTemplate = new Ext.XTemplate( '<div class="dealerInfo"><table cellpadding="0" cellspacing="0" border="0"><tbody>',
										'<tr><th>' + document.mm.settings.langName + ':</th><td>{name_1}<tpl if="this.exists(name_2)"><br />{name_2}</tpl></td></tr>',
										'<tr><th class="dealerInfoLineBottom" style="height: 3px;font-size:3px;">&nbsp;</th><td class="dealerInfoLineBottom" style="height: 3px;font-size:3px;">&nbsp;</td></tr>',
										'<tr><th>' + document.mm.settings.langAdresse + ':</th> <td>{address}<br>{postcode} {city}<br />{country_name}</td></tr>',
										'<tr><th>' + document.mm.settings.langTelefon + ':</th> <td>{phone}</td></tr>',
										'<tpl if="this.exists(fax)"><tr><th>' + document.mm.settings.langTelefax + ':</th><td>{fax}</td></tr></tpl>',
										'<tpl if="this.exists(mobile)"><tr><th>' + document.mm.settings.langMobil + ':</th><td>{mobile}</td></tr></tpl>',
										'<tpl if="this.exists(email)"><tr><th>' + document.mm.settings.langEmail + ':</th><td><a href="mailTo:{email}" target="_blank">{email}</a></td></tr></tpl>',
										'<tr><th class="dealerInfoLineBottom" style="height: 3px;font-size:3px;">&nbsp;</th><td class="dealerInfoLineBottom" style="height: 3px;font-size:3px;">&nbsp;</td></tr>',
										'<tpl if="this.exists(internet)"><tr><th>' + document.mm.settings.langWebadresse + ':</th><td><a href="http://{internet}" target="_blank">{internet}</a></td></tr></tpl>',
										'<tr><th class="dealerInfoLineBottom" style="height: 3px;font-size:3px;">&nbsp;</th><td class="dealerInfoLineBottom" style="height: 3px;font-size:3px;">&nbsp;</td></tr>',
										'<tr><th>' + document.mm.settings.langDistance + ':</th><td>{distance} {unit} ... <a href="#" onclick="document.mm.geo.getRoute(this,{index});">' + document.mm.settings.langRoutenplaner + '</a></td></tr>',
										"</tbody></table></div>",{exists:function(o){return typeof o!="undefined"&&o!==null&&o!==""}}
									);
document.mm.settings.dealerListTemplate = new Ext.XTemplate( '<div class="dealerInfoList"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tbody>',
										'<tr><th>' + document.mm.settings.langName + ':</th><td><a href="#" onclick="document.mm.geo.jumpToPoint({index});" >{name_1}<tpl if="this.exists(name_2)"><br />{name_2}</tpl></a></td></tr>',
										'<tr><th class="dealerInfoLineBottom" style="height: 3px;font-size:3px;">&nbsp;</th><td class="dealerInfoLineBottom" style="height: 3px;font-size:3px;">&nbsp;</td></tr>',
										'<tr><th>' + document.mm.settings.langAdresse + ':</th> <td>{address}<br>{zipcode} {city}<br />{country_name}</td></tr>',
										'<tr><th>' + document.mm.settings.langTelefon + ':</th> <td>{phone}</td></tr>',
										'<tpl if="this.exists(fax)"><tr><th>' + document.mm.settings.langTelefax + ':</th><td>{fax}</td></tr></tpl>',
										'<tpl if="this.exists(mobile)"><tr><th>' + document.mm.settings.langMobil + ':</th><td>{mobile}</td></tr></tpl>',
										'<tpl if="this.exists(email)"><tr><th>' + document.mm.settings.langEmail + ':</th><td><a href="mailTo:{email}" target="_blank">{email}</a></td></tr></tpl>',
										'<tr><th class="dealerInfoLineBottom" style="height: 3px;font-size:3px;">&nbsp;</th><td class="dealerInfoLineBottom" style="height: 3px;font-size:3px;">&nbsp;</td></tr>',
										'<tpl if="this.exists(internet)"><tr><th>' + document.mm.settings.langWebadresse + ':</th><td><a href="http://{internet}" target="_blank">{internet}</a></td></tr></tpl>',
										'<tr><th class="dealerInfoLineBottom" style="height: 3px;font-size:3px;">&nbsp;</th><td class="dealerInfoLineBottom" style="height: 3px;font-size:3px;">&nbsp;</td></tr>',
										'<tr><th style="padding-bottom:10px;">' + document.mm.settings.langDistance + ':</th><td>{distance} {unit} ... <a href="#" onclick="document.mm.geo.getRoute(this,{index});">' + document.mm.settings.langRoutenplaner + '</a></td></tr>',
										"</tbody></table></div>",{exists:function(o){return typeof o!="undefined"&&o!==null&&o!==""}}
									);


document.mm.dealerSearch=function()
{
	if ( document.mm.geo.gDirections )
	{
		document.mm.geo.gDirections.clear();
		document.mm.geo.gMap2.clearOverlays();
	}
	document.mm.geoCoder=document.mm.geoCoder || new GClientGeocoder();
	
	var city = document.mm.getElementById("searchCityFld").value;
	
	
	
	var country = document.mm.getElementById("countryComboBox").value;
	var radius = document.mm.settings.radius;
	var productGroup = document.mm.getElementById("productGroupComboBox").value;
	var productBrand = document.mm.getElementById("productBrandComboBox").value;
	var longitude = document.mm.getElementById("longitudeFld").value;
	var latitude = document.mm.getElementById("latitudeFld").value;
					
	/*
	var newCity = city.split("-");
	city = newCity[0];
	*/
	var address = "";
	
	for(var i = 0; i < pointMarkers.length; ++i) 
	{
		document.mm.geo.gMap2.removeOverlay(pointMarkers[i]);
	}
	pointMarkers = [];
	
	if ( city != null )
	{
		var address = address + ", " + city;
	}
	
	if ( country != null )
	{
		var address = address + ", " + country;
	}
	
	if ( city == "" )
	{
		if ( longitude != null && latitude != null )
		{
			var address = latitude + "," + longitude;
		}
	}
			
	//alert(city);
	
	document.mm.geoCoder.getLatLng(address,function(point)
	{			
		if(!point)
		{
			Ext.get("statusBar").update(document.mm.settings.langAdrNotFound).show(true);
		}
		else
		{			
			//document.mm.geo.drawCircle(point, document.mm.settings.radius/100, '#FF9601', 10, 0.5);
									
			var longitude = point.x;
			var latitude = point.y;
			
			//alert(point.x);
			//alert(point.y);
			
			dealerSearchPanel.findById("longitudeFld").setValue(longitude);
			dealerSearchPanel.findById("latitudeFld").setValue(latitude);
	
			Ext.get("statusBar").update("").show(true);
			
			if ( markerActPos != null )
			{
				document.mm.geo.gMap2.removeOverlay(markerActPos);
	        	markerActPos = null;
			}

			document.mm.geo.addMarkerActPos( point );			
						
			document.mm.getElementById('loading').style.visibility='visible';
			
			Ext.Ajax.request({
			    params : { action : 'getDealersLanLog', city : city, country : country, radius : radius, maxResult : document.mm.settings.maxResult, longitude : longitude, latitude : latitude, productGroup : productGroup, productBrand : productBrand },
			    url: document.mm.settings.requestUrl,
			    method: 'POST',
			    success: function(result, request){
			    	var jResponse = '';
			    	var actionContent = '';
					eval( 'var jResponse = (' + result.responseText.trim() + ')' );
					if ( jResponse['status'] == 'ok' ) {
					 	Ext.get("statusBar").update(jResponse['dataCount']+document.mm.settings.langResult).show(true);
					 	var i = 0;
					 	for ( var objId in jResponse['data'] )
						//for each ( var item in jResponse['data'] )
						{
							var item = jResponse['data'][objId];
							if ( item.name_1 != "" && item.name_1 != null )
							{
								var point = new GLatLng( item.latitude, item.longitude );
								var data = {
								    name_1: item.name_1,
								    name_2: item.name_2,
								    address: item.address,
								    zipcode: item.zipcode,
								    city: item.city,
								    phone: item.phone,
								    fax: item.fax,
								    mobile: item.mobile,
								    email: item.email,
								    internet: item.internet,
								    internetHref: 'http://'+item.internet,
								    country_name: item.country_name,
								    distance: item.distance,
								    unit: item.unit,
								    index: i
								};
								
								var info = document.mm.settings.qtipTemplate.applyTemplate(data);
								pointMarkers[i] = document.mm.geo.addMarkerDealer( point, info );
								pointMarkersInfo[i] = info;
								
								var dealer = document.mm.settings.dealerListTemplate.applyTemplate(data);
								actionContent = actionContent + dealer;
								i++;
							}
						}
						actionPanel.expand(true);
						document.mm.settings.actionPanelExpanded=true;
						Ext.get("actionPanelContent").update(actionContent);
					}
					else
					{
					 	Ext.get("statusBar").update(document.mm.settings.langNoResult).show(true);
					}
					document.mm.getElementById('loading').style.visibility='hidden';
			    }
			});
		}
	})
};

document.mm.geo.addMarkerDealer = function( point, info )
{
	var markerNew = document.mm.geo.createMarker( point, document.mm.settings.mapDealerMarkerColor );
	
	markerNew.disableDragging();
	
	GEvent.addListener(markerNew, "click", function() {
		document.mm.geo.gMap2.openInfoWindowHtml(point, info );
	});

	document.mm.geo.gMap2.addOverlay(markerNew);
			
	return markerNew;
}

document.mm.geo.addMarkerActPos = function( point )
{		
	markerActPos = document.mm.geo.createMarker( point, document.mm.settings.mapLocationMarkerColor );
	markerActPos.enableDragging();
		
	markerActPosClick = GEvent.addListener(markerActPos, "click", function() {
		document.mm.geo.gMap2.openInfoWindowHtml(point, document.mm.settings.langPosition );
	});
		
	
	GEvent.addListener(markerActPos, "drag", function() {
		document.mm.settings.actLatitude = markerActPos.getPoint().y;
		document.mm.settings.actLongitude = markerActPos.getPoint().x;
		document.mm.getElementById('latitudeFld').value = markerActPos.getPoint().y;
		document.mm.getElementById('longitudeFld').value = markerActPos.getPoint().x;
		document.mm.getElementById('searchCityFld').value = '';
		
		GEvent.removeListener(markerActPosClick);
		markerActPosClick = GEvent.addListener(markerActPos, "click", function() {
			document.mm.geo.gMap2.openInfoWindowHtml(markerActPos.getPoint(), document.mm.settings.langPosition );
		});
	});
		
	
	GEvent.addListener(markerActPos, "dragend", function() {
		document.mm.dealerSearch();
	});
	
	document.mm.geo.gMap2.addOverlay(markerActPos);
}

// Move the map to the selected point in the point list.
document.mm.geo.jumpToPoint = function( index ) 
{		
	var point = pointMarkers[index].getLatLng();
	
	document.mm.geo.gMap2.setCenter(new GLatLng(point.lat(), point.lng()), document.mm.geo.gMap2.getZoom());
	
	if (pointMarkers[index] != null && pointMarkers[index] != highlightedMarker) {
		document.mm.geo.gMap2.removeOverlay(pointMarkers[index]);
	}
	
	if (highlightedMarker != null) {
		var oldIndex = document.mm.geo.findMarkerIndex(highlightedMarker);
		document.mm.geo.gMap2.removeOverlay(highlightedMarker);
	
		if (oldIndex != index) {
			pointMarkers[oldIndex] = document.mm.geo.addMarkerDealer(highlightedMarker.getPoint(), pointMarkersInfo[oldIndex]);
			document.mm.geo.gMap2.addOverlay(pointMarkers[oldIndex]);
		}
	}
	
	var colMerker = document.mm.settings.mapDealerMarkerColor;
	document.mm.settings.mapDealerMarkerColor = document.mm.settings.mapDealerMarkerColorHighlight;
	highlightedMarker = document.mm.geo.addMarkerDealer(pointMarkers[index].getPoint(), pointMarkersInfo[index]);
	document.mm.settings.mapDealerMarkerColor = colMerker;
	
	pointMarkers[index] = highlightedMarker;
	document.mm.geo.gMap2.addOverlay(highlightedMarker);
}

// Returns the index of the marker in the polyline.
document.mm.geo.findMarkerIndex = function(point_marker) {
	var index = -1;
	
	for (var  i = 0; i < pointMarkers.length; ++i) {
		if (pointMarkers[i] == point_marker) {
			index = i;
			break;
		}
	}
	
	return index;
}

document.mm.geo.createMarker = function(point, color ) {
	var f = new GIcon();
	switch ( color )
	{
		case 'black':
		case 'white':
		case 'grey':
		case 'yellow':
		case 'purple':
		case 'orange':
		case 'blue':
		case 'red':
		case 'green':
		default:
			f.image = "http://labs.google.com/ridefinder/images/mm_20_" + color + ".png";
			f.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
			f.iconSize = new GSize(12,20);
			f.shadowSize = new GSize(22,20);
			f.iconAnchor = new GPoint(6,20);
			f.infoWindowAnchor = new GPoint(6,1);
			f.infoShadowAnchor = new GPoint(13,13);
			break;
	}
	
	newMarker = new GMarker(point, {icon: f, draggable: true} );

	return newMarker;
}

document.mm.geo.getRoute = function( e, index )
{	
	e.style.visibility = 'hidden';	
	document.mm.getElementById('loading').style.visibility='visible';
	Ext.get("actionPanelContent").update('<i>' + document.mm.settings.langYourRouteDesc + ':</i>');
	document.mm.geo.gDirections=new GDirections(document.mm.geo.gMap2, document.mm.getElementById("actionPanelContent")); 
	document.mm.geo.gDirections.clear();
	//document.mm.geo.gMap2.clearOverlays();
	
	GEvent.addListener(document.mm.geo.gDirections,"error",function(){ 
		Ext.get("statusBar").update(
			(
				document.mm.geo.gDirections.getStatus().code==G_GEO_UNKNOWN_ADDRESS ? document.mm.settings.langAdrNotFound : 
				document.mm.geo.gDirections.getStatus().code==G_GEO_SERVER_ERROR ? "Fehler bei der \u00DCbertragung." : 
				document.mm.geo.gDirections.getStatus().code==G_GEO_MISSING_QUERY ? "Query missing." : 
				document.mm.geo.gDirections.getStatus().code==G_GEO_TOO_MANY_QUERIES ? document.mm.settings.lang2much : 
				document.mm.geo.gDirections.getStatus().code==G_GEO_UNKNOWN_DIRECTIONS ? document.mm.settings.langNoRoute : 
				document.mm.geo.gDirections.getStatus().code==G_GEO_MISSING_ADDRESS ? document.mm.settings.langNoAdr : 
				document.mm.geo.gDirections.getStatus().code==G_GEO_BAD_KEY ? "Falscher Key." : 
				document.mm.geo.gDirections.getStatus().code==G_GEO_BAD_REQUEST ? document.mm.settings.langNoRoute1 :
				"Unbekannter Fehler.")).show(true);
		actionPanel.expand(false);
		actionPanelExpanded=false;
	});
			
	var point0 = pointMarkers[index].getLatLng();
	var point1 = markerActPos.getLatLng();
	
	//var query = "from: " + point0.lat() + ', ' + point0.lng() + " to: " + point1.lat() + ', ' + point1.lng();
	var query = "from: " + point1.lat() + ', ' + point1.lng() + " to: " + point0.lat() + ', ' + point0.lng();

	for(var i = 0; i < pointMarkers.length; ++i) {
		document.mm.geo.gMap2.removeOverlay(pointMarkers[i]);
	}
	pointMarkers = [];
		
	document.mm.geo.gDirections.load(query,{locale:"de_DE",getPolyline:true,getSteps:true});

	GEvent.addListener(document.mm.geo.gDirections, "click", function(overlay, point) {
	  	if ( point )
	  	{
		    document.mm.settings.actLatitude = point.y;
		    document.mm.settings.actLongitude = point.x;
		    document.mm.getElementById('latitudeFld').value = point.y;
			document.mm.getElementById('longitudeFld').value = point.x;
			document.mm.getElementById('searchCityFld').value = '';
			
		    dealerSearchPanel.expand(true);     
		    if (markerActPos == null) {
				document.mm.geo.addMarkerActPos( point );
	
		    } 
		    else 
		    {
		      markerActPos.setPoint(point);
	
		    }
		    GEvent.removeListener(markerActPosClick);
		    markerActPosClick = GEvent.addListener(markerActPos, "click", function() {
				document.mm.geo.gDirections.openInfoWindowHtml(point, document.mm.settings.langPosition );
			});
	  	}  	
  	});
	  
	Ext.get("statusBar").update("Route wurde berechnet.").show(true);
	actionPanel.expand(true);
	actionPanelExpanded=true;
	
	document.mm.getElementById('loading').style.visibility='hidden';
}

document.mm.geo.addMapClickListener = function()
{
	if ( document.mm.geo.gMap2 )
	{
		GEvent.addListener(document.mm.geo.gMap2, "click", function(overlay, point) {
			if ( point )
			{
			    document.mm.settings.actLatitude = point.y;
			    document.mm.settings.actLongitude = point.x;
			    document.mm.getElementById('latitudeFld').value = point.y;
				document.mm.getElementById('longitudeFld').value = point.x;
				document.mm.getElementById('searchCityFld').value = '';
				
			    dealerSearchPanel.expand(true);
			    if (markerActPos == null) {
					document.mm.geo.addMarkerActPos( point );
			    }
			    else 
			    {
			      markerActPos.setPoint(point);
			    }
			    
			    GEvent.removeListener(markerActPosClick);
			    markerActPosClick = GEvent.addListener(markerActPos, "click", function() {
					document.mm.geo.gMap2.openInfoWindowHtml(point, document.mm.settings.langPosition );
				});
				
				document.mm.dealerSearch();
				document.mm.geo.gMap2.setCenter( point, document.mm.settings.zoom );
			}  	
		});
	}
}

var oldCircle = [];

function eraseCircles() {
	if(oldCircle) {
		for (var i = 0; i < oldCircle.length; i++) {
			map.removeOverlay(oldCircle[i]);
		}
		oldCircle = [];
	}
}
document.mm.geo.drawCircle = function(center, radius, color, thickness, opacity) {
	//Function created by Chris Haas
	var circleQuality = 1; //1 is best but more points, 5 looks pretty good, too
	var M = Math.PI / 180; //Create Radian conversion constant
	var L = document.mm.geo.gMap2.getBounds(); //Holds copy of map bounds for use below
	var sw = L.getSouthWest();
	var ne = L.getNorthEast();
		
	//The map is not completely square so this calculates the lat/lon ratio
	// this works because we create a square map
	var circleSquish = (ne.lng() - sw.lng()) / (ne.lat() - sw.lat());
	
	var points = []; //Init Point Array
	//Loop through all degrees from 0 to 360
	for(var i=0; i<360; i+=circleQuality){
		var P = new GLatLng(
			center.lat() + (radius * Math.sin(i * M)),
			center.lng() + (radius * Math.cos(i * M)) * circleSquish
		);
		points.push(P);
	}
	points.push(points[0]); // close the circle
	var p = new GPolyline(points, color, thickness, opacity)
	document.mm.geo.gMap2.addOverlay(p);
	oldCircle.push(p);
}

 
