var canvas = null;
var address = "";
var locations = null;
var micon = null;
var geocoder;
var markers = [];
var markerImage;
var infoWindow;

function initialize() {
	geocoder = new google.maps.Geocoder();
	markerImage = new google.maps.MarkerImage("/Files/HTML/storelocator/icons/gmap_pointer.png",new google.maps.Size(27, 33),new google.maps.Point(0, 0), new google.maps.Point(15, 15));
	infoWindow = new google.maps.InfoWindow();
	createMapV3();
}

function createMapV3() {
	var myLatlng = new google.maps.LatLng(55.677584411089526, 12.5408935546875);
	var myOptions = {
            zoom: 2,
            center: myLatlng,
            disableDefaultUI: false,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: false,
            navigationControl: true,
            navigationControlOptions: {
                position: google.maps.ControlPosition.RIGHT
            }
    };
	canvas = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}

function removeMarkers() {
	for ( var i = 0; i < markers.length; i++ ) {
		markers[i].setMap(null);	
	}
	markers = [];
}

function centerOnAddress( address ) {
    geocoder.geocode({ 'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                canvas.setCenter(results[0].geometry.location);
                
            } else {
				alert(translations.nosearchresults);
                //alert("Din soegning gav ingen resultater: " + status);
            }
    });    
}

function onMarkerPressed( marker ) {	
	canvas.panTo(marker.getPosition());	
}

$(document).ready(function()
{	
	initialize();
	$("#fCountry").change(function()
	{
		if($("#fCountry option:selected").val() == "www")
		{
			loadWWW();
		}
		else if($("#fCountry option:selected").val() == "cc")
		{ 
		//do nada
		}		
		else
		{
			centerOnAddress($("#fCountry option:selected").text());
			canvas.setZoom(6);
		}
	});
		
	$("#searchinput").click(function(e){
		e.preventDefault();
		Search_Click();
	});
	$("#txtZipcode").keydown(Enter_Pressed);	
});

function Enter_Pressed(e)
{
	if (e.keyCode == '13') 
	{
		e.preventDefault();
		Search_Click();
	}
}


function unloadWWW()
{	
}

function Search_Click(iscallback) 
{	
	locations = null;
	if($.trim($("#txtZipcode").val()) != "" && $("#fCountry option:selected").val() != "cc" && $("#fCountry option:selected").val() != "www"   )
	{
		unloadWWW();	
		canvas.setZoom(12);
		centerOnAddress($("#txtZipcode").val()+", "+$("#fCountry option:selected").text());
		$("#physDealers ul").html("");
		if(iscallback == true)
		{		
			$.ajax({
			   type: "POST",
			   url: "/fLocator.aspx?action=getClosestLocations&top=10",
			   data: {positionLat:/*canvas.currentPoint.lat()*/canvas.getCenter().lat(), positionLng:/*canvas.currentPoint.lng()*/canvas.getCenter().lng(), country:$("#fCountry option:selected").val()},
				success: function(msg)
				{
					removeMarkers();					
					locations = eval("(" +msg + ")");	
					/*$("#divSearchResults").html("");
					$("#divSearchResults").append("<dl id='list'></dl>");
					$("#divSearchResults #list").append("<dt>The dealers nearest you:<br /><br /></dd>");*/
					for(i = 0; i < locations.length; i++)
					{
						locations[i].NiceDistance = $.decimals(locations[i].Distance,1);
						var templateStr = "<li><a title='${Address}, ${City} ("+translations.distance+":${NiceDistance} km)' href='javascript:PanToLocation(${Id})'><strong>${Name}</strong></a></li>";
						/*var templateStr = 
							"<dd>"+
							"<a title='${Address}, ${City} (afstand:${NiceDistance} km)' href='javascript:PanToLocation(${Id})'>${Name}</a>"+
							"</dd>";*/
							
						var t = $.template(templateStr);
						$("#physDealers ul").append(t, locations[i]);
						$("#physDealers").show();
						//$("#divSearchResults #list").append(t, locations[i]);
						MakeMarker(new google.maps.LatLng(locations[i].Lat, locations[i].Lng), locations[i]);
					}			
				}
			 });		
		}
		else
		{
			setTimeout(function(){Search_Click(true);}, 1000);
		}
	}
}

function MakeMarker(point, location) 
{
	var marker = new google.maps.Marker({
		position: point,
		map: canvas,
		icon: markerImage,		
		visible: true
	});

	google.maps.event.addListener(marker, 'click', function() {
		onMarkerPressed(marker);		
		infoWindow.setPosition(point);
		infoWindow.setContent(GetHtml(location));
		infoWindow.open(canvas);
	});	
	markers.push(marker);	
}

function PanToLocation(id)
{	
	var location = GetLocation(id);
	canvas.setZoom(12);
	canvas.panTo(new google.maps.LatLng(location.Lat, location.Lng));
	//centerOnAddress(location.Zip +", "+location.Country);	
	infoWindow.setPosition(new google.maps.LatLng(location.Lat, location.Lng));
	infoWindow.setContent(GetHtml(location));
	infoWindow.open(canvas);
}

function loadByAddress(location)
{	
	canvas.setZoom(12);
	
	var country = "Denmark";
	console.log("location.Country: " + location.Country);
	if ( location.Country != undefined ) {
		country = location.Country;
	}
	
	geocoder.geocode({ 'address': location.Zip+", " + country}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			canvas.setCenter(results[0].geometry.location);
			infoWindow.setPosition(results[0].geometry.location);
			infoWindow.setContent(GetHtml(location));
			infoWindow.open(canvas);
			
		} else {
			alert("Din soegning gav ingen resultater: " + status);
		}
    }); 
}

function GetLocation(id)
{	
	for(i = 0; i < locations.length; i++)
	{
		if(locations[i].Id == id)
			return locations[i];
	}
	return null;
}
function GetHtml(location)
{	
	return "<div style='font-size:11px;'><b>"+location.Name+"</b><br />"+location.Address+"<br />"+location.Zip+" "+location.City+"<br /><p class='tel phone'>Tlf: "+location.Phone+"</p></div>";
}

function GetLink(href)
{
	if(Base.IsStringEmpty(href))
		return "";
	else 
		return
			"<a target='blank' href='http://"+href+"'>"+href+"</a>";						  
}
