﻿var center = new VELatLong(51, 10);
var pinServiceUrl = "returnresults.php";
var map = null;
var dataLayer = new VEShapeLayer();
var shapeData = null;
var searchShape = null;
var customIcon = "pin1.gif";
var clusterIcon = "pin1_more.gif";

function GetMap(mapDivName)
{
    map = new VEMap(mapDivName);
    map.SetCredentials("AkCDmfqmo0PznhpLv3EoQk86qyKniz6QhySIoil0u2KOOvOnuCd9tH4xDHa-7pEI");
    map.SetDashboardSize(VEDashboardSize.Small);
    map.LoadMap(center, 6, VEMapStyle.Shaded, false, VEMapMode.Mode2D);
    map.AddShapeLayer(dataLayer);
    
    var clusteringOptions = new VEClusteringOptions();
	  var customIcon = new VECustomIconSpecification();
	  customIcon.Image = clusterIcon;
	  clusteringOptions.Icon = customIcon;
	  clusteringOptions.Callback = customCallback;
	  dataLayer.SetClusteringConfiguration(customClusterAlgorithm, clusteringOptions);
}

function FindLoc()
{
    var txtWhere = document.getElementById('txtWhere');
    var country = document.getElementById('countrySelect').value;
    var searchString = txtWhere.value;
    
    if(searchString.length == 0)
    {
    	alert("Bitte geben Sie eine gültige Adresse in das Suchfeld ein.");
    	return;
    }
    
    switch(country)
    {
        case '1':
            searchString += ", Germany";
            break;
        case '2':
            searchString += ", Austria";
            break;
        case '3':
            searchString += ", Switzerland";
            break;
        case '4':
            searchString += ", Netherlands";
            break;
        case '5':
            searchString += ", Belgium";
            break;
        case '6':
            searchString += ", Luxembourg";
            break;
        case '7':
            searchString += ", France";
            break;
        case '8':
            searchString += ", Czech Republic";
            break;
        case '9':
            searchString += ", Poland";
            break;
        case '10':
            searchString += ", Denmark";
            break;
        default:
            break;
    }
    
    map.Find(null,searchString,null,dataLayer,null,10,true,true,true,false,findCallback);
}

function findCallback(layer, resultsArray, places, hasMore, veErrorMessage)
{
    if(places != null)
    {
    		dataLayer.DeleteAllShapes();
    		map.DeleteAllShapes();
    		var shapeTitle = "Suchergebnis:<br />" + places[0].Name;
    		var latitude = places[0].LatLong.Latitude;
    		var longitude = places[0].LatLong.Longitude;
    		searchShape = new VEShape(VEShapeType.Pushpin, places[0].LatLong);
    		center = places[0].LatLong;
    		searchShape.SetTitle("");
    		searchShape.SetCustomIcon("poi_usergenerated_small.gif");
        $.getJSON(pinServiceUrl, {lat: latitude, lon: longitude}, GetPinsCallback);
    }
    else
  	{
  		alert("Zu dieser Eingabe wurden keine Ergebnisse gefunden.");
  	}
}

function GetPinsCallback(jsonData)
{
		var iconUrl = "";
		shapeData = new Object();
		var maxLat = -85;
    var minLat = 85;
    var maxLon = -180;
    var minLon = 180;

    $.each(jsonData, function(i, item)
    {
				var focus = "";
				
				if(item.focus != "")
				{
					if(item.focus == "JOSERA" || item.focus == "AGRAR")
					{
						focus = " <img src='" + iconUrl + "HKP.gif' border='0' alt='Schwerpunkt' />";
					}
					else if(item.focus == "H" || item.focus == "HK" || item.focus == "HKP" || item.focus == "HP" || item.focus == "K" || item.focus == "P")
					{
						focus = " <img src='" + iconUrl + item.focus + ".gif' border='0' alt='Schwerpunkt' />";
					}
				}
				
				var certified = (item.certified == "1" ? "<img src='" + iconUrl + "certified.jpg' border='0' alt='Zertifiziert' />" : "");
				var business = (item.business == "1" ? "<img src='" + iconUrl + "business.gif' border='0' alt='Geschäft' />" : "");
        var delivery = (item.delivery == "1" ? " <img src='" + iconUrl + "lkw.gif' border='0' alt='Lieferservice' />" : "");
        var title = "<div>" + business + delivery + focus + certified + "</div>";
        
        var street = (item.business == "1" ? "<div>" + item.address2 + "</div>" : "");
        var postal = "<div>" + item.postcode + " " + item.city + (item.district != "" ? " OT: " + item.district : "") + "</div>";
        var tel = (item.phoneNo != "" ? "<div><span>Tel.: </span>" + item.phoneNo + "</div>" : "");
        var mobil = (item.mobilePhone != "" ? "<div><span>Mobil: </span>" + item.mobilePhone + "</div>" : "");
        var email2 = (item.eMail != "" ? "<div><a href=\"mailto:" + item.eMail + "\">" + item.eMail + "</a></div>" : "");
        var homepage = (item.homepage != "" ? "<div><a href=\"http://" + item.homepage + "\" target=\"_blank\">" + item.homepage + "</a></div>" : "");
        var businessHours = (item.businessHours != "" ? "<div><b>Öffnungszeiten:</b> " + item.businessHours + "</div>" : "");
        
        var description = "<div>"
            + "<div style='font-weight:bold;'>" + item.name2 + " " + item.address + "</div>"
            + "<div style='font-weight:bold;'>" + item.name + "</div>"
            + street + postal
            + "<br />" + tel + mobil + email2 + homepage + "<br />" + businessHours
            + "</div>";
    		
        var shapeId = AddPushpin(title, description, new VELatLong(item.latitude, item.longitude));
        shapeData[shapeId] = new Object();
        shapeData[shapeId]["name"] = item.name2 + " " + item.name;
        shapeData[shapeId]["address"] = postal;
        shapeData[shapeId]["title"] = title;
        shapeData[shapeId]["description"] = description;
        
        var tempLat = Number(item.latitude);
        var tempLon = Number(item.longitude);
                
        if (tempLat > maxLat)
        {
            maxLat = tempLat;
        }

        if (tempLat < minLat)
        {
            minLat = tempLat;
        }

        if (tempLon > maxLon)
        {
            maxLon = tempLon;
        }

        if (tempLon < minLon)
        {
            minLon = tempLon;
        }
    });
    
    if (center.Latitude > maxLat)
    {
        maxLat = center.Latitude;
    }

    if (center.Latitude < minLat)
    {
        minLat = center.Latitude;
    }

    if (center.Longitude > maxLon)
    {
        maxLon = center.Longitude;
    }

    if (center.Longitude < minLon)
    {
        minLon = center.Longitude;
    }
    
    map.AddShape(searchShape);
    var mapView = BestMapView(center, maxLat, minLat, maxLon, minLon, 5);
    map.SetMapView(mapView);
}

function AddPushpin(title, description, latLon)
{
    var shape = new VEShape(VEShapeType.Pushpin, latLon);
    shape.SetCustomIcon(customIcon);
    shape.SetTitle(title);
    shape.SetDescription(description);
    dataLayer.AddShape(shape);
    return shape.GetID();
}

function setShapeDescription(shapeId1, shapeId2)
{
	document.getElementById(shapeId2 + '_ContentTitle').innerHTML = shapeData[shapeId1]["title"];
	document.getElementById(shapeId2 + '_Content').innerHTML = shapeData[shapeId1]["description"];
	return false;
}

function customClusterAlgorithm(clusterLayer)
{
    var clusterSpecificationArray = new Array();
    var n = clusterLayer.GetShapeCount();
    
    if (n > 0) 
    {
        var shape0 = clusterLayer.GetShapeByIndex(0);
        var point0 = shape0.GetPoints()[0];
        var clusterSpecification = null;
        
        for(var i = 1; i < n; i++)
        {
            var shape1 = clusterLayer.GetShapeByIndex(i);
            var point1 = shape1.GetPoints()[0];
            
            if (Overlap(point0, point1))
            {
                if (clusterSpecification == null)
                {
                    clusterSpecification = new VEClusterSpecification();
                    clusterSpecification.Shapes = new Array();
                    clusterSpecification.Shapes.push(shape0);
                }
                
                clusterSpecification.Shapes.push(shape1);
                clusterSpecification.LatLong = point1;
                
                if (i == n-1)
                    clusterSpecificationArray.push(clusterSpecification);   
            }
            else
            {
                if (clusterSpecification != null)
                {
                    clusterSpecificationArray.push(clusterSpecification);
                    clusterSpecification = null;
                }
            }
           
            shape0 = shape1;
            point0 = point1;     
        }
    }
    
    return clusterSpecificationArray;
}

function Overlap(point0, point1)
{
    var distance = 12;
	  var pixel0 = map.LatLongToPixel(point0);
	  var pixel1 = map.LatLongToPixel(point1);
    return (Math.abs(pixel0.x - pixel1.x) < distance && Math.abs(pixel0.y - pixel1.y) < distance);
}

function customCallback(clusterSpecificationArray)
{
    for (var i=0; i < clusterSpecificationArray.length; ++i)
    {
        var clusterSpecification = clusterSpecificationArray[i];
        var clusterShape = clusterSpecification.GetClusterShape();
        var shapes = clusterSpecification.Shapes;
        var title = "<div id='" + i + "_ContentTitle'>" + shapes.length + " H&auml;ndler an diesem Standort vorhanden. Klicken oder verg&ouml;&szlig;ern Sie, um Details zu erhalten.</div>";
	      var description = "<div id='" + i + "_Content'><ul style='padding-left:8px;margin-left:8px;'>";
        clusterShape.SetTitle(title);
        
        for (var j = 0; j < shapes.length; j++)
        {
            var shape = shapes[j];
            var shapeId = shape.GetID();
            
            if(shapeData[shapeId])
            	description += "<li>" + shapeData[shapeId]["name"] + " <div style='text-decoration: underline;color:blue;cursor:pointer;' onclick='setShapeDescription(\"" + shapeId + "\", \"" + i + "\");'>" + shapeData[shapeId]["address"] + "</div></li>";
        }
        
        description += "</ul></div>"
        clusterShape.SetDescription(description);
    }
}

function BestMapView(center, maxLat, minLat, maxLon, minLon, buffer)
{
    var mapView = null;
    var zoomLevel = 0;
    var mapWidth = 548;
    var mapHeight = 500;
    var zoom1=9, zoom2=9;

    //Determine the best zoom level based on the map scale and bounding coordinate information
    if (maxLon != minLon && maxLat != minLat)
    {
        //best zoom level based on map width
        zoom1 = Math.log(360.0 / 256.0 * (mapWidth - 2*buffer) / (maxLon - minLon)) / Math.LN2;
        //best zoom level based on map height
        zoom2 = Math.log(180.0 / 256.0 * (mapHeight - 2*buffer) / (maxLat - minLat)) / Math.LN2;
    }

    //use the most zoomed out of the two zoom levels
    zoomLevel = (zoom1 < zoom2) ? zoom1 : zoom2;
    mapView = new VEMapViewSpecification(center, Math.floor(zoomLevel));

    return mapView;
}