var storeIconImagePath = null;
var userIconImagePath = null;
var storeInfoDisplayText = null;
var userInfoDisplayText = null;
var mapZoom = 15;
var storeLatitude = 56.154459;
var storeLongitude = 10.206777;
var directionsDisplay = null;

var mapCanvasElementId = 'map_canvas';

var gMap = null; 
var initialLocation;
var infowindow;
var geoCoder = null;

function initializeGoogleMap(storeLatitude, storeLongitude, storeIconImageUrl, userIconImageUrl, ignoreNearestLocation)
{
    var mapCanvasElement = document.getElementById(mapCanvasElementId);
     if(mapCanvasElement == null)
     {
        return;
     }
	 if(gMap == null)
	 {
		 infowindow = new google.maps.InfoWindow();
		 var storeLatlng = new google.maps.LatLng(storeLatitude, storeLongitude);
		  var myOptions = {
			zoom: mapZoom,
			center: storeLatlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		  };
		  gMap = new google.maps.Map(mapCanvasElement, myOptions);
	  }
	  else
	  {
		gMap.clearMarkers();
	  }
    AddMarkers(storeLatitude, storeLongitude, storeIconImageUrl, userIconImageUrl, ignoreNearestLocation);
}

function AddMarkers(storeLatitude, storeLongitude, storeIconImageUrl, userIconImageUrl,ignoreNearestLocation)
{
     initializeMarkers();
      
     var storeImage = getMarkerImage(storeIconImagePath);
     var userImage =  getMarkerImage(userIconImagePath);

     if (ignoreNearestLocation == undefined || ignoreNearestLocation == null) {
         if (navigator.geolocation) {
             browserSupportFlag = true;
             navigator.geolocation.getCurrentPosition(onSuccess, null);
         }
         else if (google.gears) {
             browserSupportFlag = true;
             var geo = google.gears.factory.create('beta.geolocation');
             geo.getCurrentPosition(onSuccess, null);
         }
     }
      
      var mapBounds = new google.maps.LatLngBounds();
      
      function onSuccess(position) 
	  { 
        initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
        
        if(initialLocation != null){
            AddMarker(userInfoDisplayText, initialLocation, mapBounds, userImage);
        }
        else{
          gMap.setCenter(new google.maps.LatLng(storeLatitude, storeLongitude));
        }
		if(gMap.markers.length > 1)
		{
			gMap.fitBounds(mapBounds);
			gMap.setCenter(mapBounds.getCenter());
			
			directionsDisplay = new google.maps.DirectionsRenderer();
			var directionsService = new google.maps.DirectionsService();

			var request = {
				origin:  initialLocation, 
				destination: new google.maps.LatLng(storeLatitude, storeLongitude),
				travelMode: google.maps.DirectionsTravelMode.DRIVING
			};

			directionsService.route(request, function (result, status) {
			    if (status == google.maps.DirectionsStatus.OK) {
			        directionsDisplay.setDirections(result);			        
			        directionsDisplay.setMap(gMap);
			    }
			});
		}
      }
	AddMarker(storeInfoDisplayText, new google.maps.LatLng(storeLatitude, storeLongitude), mapBounds, storeImage); 
	if(gMap.markers.length > 1)
	{
	    gMap.fitBounds(mapBounds);
	    gMap.setCenter(mapBounds.getCenter());	    
	}
	else {
	   
		gMap.setCenter(new google.maps.LatLng(storeLatitude, storeLongitude));
		gMap.setZoom(8);
		//alert("test");
	}
}

function getMarkerImage(iconImagePath)
{
    if (iconImagePath !=null && iconImagePath !="") 
     { 
        return new google.maps.MarkerImage(iconImagePath, 
                new google.maps.Size(16, 16), 
                new google.maps.Point(0, 0), 
                new google.maps.Point(32, 52) 
        ); 
     }
     
     return null;
}

// Add functionality to clear markers 
function initializeMarkers() 
{ 
    google.maps.Map.prototype.markers = new Array(); 
    google.maps.Map.prototype.addMarker = function(marker) 
        { 
        this.markers[this.markers.length] = marker; 
    }; 
    google.maps.Map.prototype.getMarkers = function() 
        { 
        return this.markers 
    }; 
    google.maps.Map.prototype.clearMarkers = function() 
        { 
        for (var i = 0; i < this.markers.length; i++) 
                { 
            this.markers[i].setMap(null); 
                        this.markers[i] = null; 
        } 
                this.markers = new Array(); 
                
    }; 
} 

// AddMarker method will attach the click event to the google map marker. 
// it will will also configure the image icon and google store detail page on the google map marker 
function AddMarker(address, point, mapBounds, markerImage) 
{
    var marker= null; 
    if (markerImage !=null) 
    { 
            marker = new google.maps.Marker( 
                { 
            position: point, 
            map: gMap, 
            icon: markerImage, 
            title: address 
        });
    } 
    else 
    { 
        marker = new google.maps.Marker( 
        { 
            position: point, 
            map: gMap, 
            title: address 
        }); 
    } 
     if(gMap.markers.length < 5) 
     {         
         mapBounds.extend(point); 
     } 
     gMap.addMarker(marker); 
     if(address != null && address != "")
     {
        infowindow.setContent(address);
        infowindow.setPosition(point);
        infowindow.open(gMap);
    }

    return marker;
}


function setToNearestLocation() {
    rtnflg = false;
    if (navigator.geolocation) {
        browserSupportFlag = true;
        navigator.geolocation.getCurrentPosition(function (position) {
            rtnflg = true;
            initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            var mapBounds = new google.maps.LatLngBounds();

            gMap.fitBounds(mapBounds);
            nearestStorePosition = findNearestStore(initialLocation);
            gMap.setCenter(nearestStorePosition);
            var directionsService = new google.maps.DirectionsService();
            if (directionsDisplay == null) {
                directionsDisplay = new google.maps.DirectionsRenderer();
            }

            var request = {
                origin: initialLocation,
                destination: new google.maps.LatLng(nearestStorePosition.lat(), nearestStorePosition.lng()),
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            };

            directionsService.route(request, function (result, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setMap(null);
                    directionsDisplay.setDirections(result);
                    directionsDisplay.setMap(gMap);
                }
            });

            gMap.setZoom(15);
        }, function () {
            rtnflg = false;
        });
    }
    return rtnflg;
}


function findNearestStore(location) {
    var distance = 6371;
    var nearestLocation = null;
    var lat = location.lat();
    var lon = location.lng();
    //alert(gMap.markers.length);
    for (var i = 0; i < gMap.markers.length; i++) {
        location2 = gMap.markers[i].getPosition();
        var lat2 = location2.lat();
        var lon2 = location2.lng();
        var curDistance = getDistance(lat, lon, lat2, lon2);
        if (curDistance < distance) {
            distance = curDistance;
            nearestLocation = location2;
        }
    }
    //alert(nearestLocation.lat()+ ":" + nearestLocation.lng());
    return nearestLocation;
}

function getDistance(lat1, lon1, lat2, lon2) {

    var R = 6371; // km 
    var dLat = toRad(lat2 - lat1);
    var dLon = toRad(lon2 - lon1);
    var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = R * c;
    return d;
}

function toRad(deg) {
    return deg * Math.PI / 180;
}

function AddMarkerByAddress(address, mapBounds) {


    if (geoCoder == null) {
        try {
            geoCoder = new google.maps.Geocoder();
        }
        catch (e) {
            alert("GeoCode cannot be initialized." + e.ToString());
            return;
        }
    }

    if (geoCoder != null) {

        geocoder.geocode({ 'address': address },
           function (results, status) {
               if (status == google.maps.GeocoderStatus.OK) {
                   return AddMarker(address, results[0].geometry.location, mapBounds,null);
               }
           });
    }
   }


function AddStoreMarkers(stores,drawNearestLine) {
   
//    if (gMap != null) {
//        gMap.clearMarkers(); // clearMarkers
    //    }
    removeAllMarkers();
    for (var index = 0; index < stores.length; index++) {

        address = "";
        var storeId = "";

        if (stores[index] != null && stores[index] != "") {

            if (stores[index].Address != null && stores[index].Address != "") {
                storeId = stores[index].StoreId;
            }

            if (stores[index].Address != null && stores[index].Address != "") {
                address += stores[index].Address + " ";
            }
            if (stores[index].PostalCode != null && stores[index].PostalCode != "") {
                address += stores[index].PostalCode + " ";
            }
            if (stores[index].CityName != null && stores[index].CityName != "") {
                address += stores[index].CityName + " ";
            }

            if (address != null && address != "") {

                var mapBounds = new google.maps.LatLngBounds();
                var marker = null;
                address += "Denmark";
                if ((stores[index].Latitude != null && stores[index].Latitude != "") &&
                                (stores[index].Longitude != null && stores[index].Longitude != "")) {
                    var point = new google.maps.LatLng(stores[index].Latitude, stores[index].Longitude);
                    //alert("point method");
                    marker = AddMarker(address, point, mapBounds, null);
                }
                else {

                    //alert("address method");
                    marker = AddMarkerByAddress(address, mapBounds);
                }

                addStoreClick(marker, storeId);              

            } // ending of if address 

        }
        
    }


    if (drawNearestLine != undefined && drawNearestLine != null) {       
        if (!setToNearestLocation()) {
            // implementatin later on.
        }
    }  
}


function addStoreClick(marker,storeId) {

    google.maps.event.addListener(marker, 'click',
               function () {

                   var showInNewWindow = true;

                   if (window.location.toString().indexOf(DETAIL_MAP_PAGE_URL) > -1) {
                       showInNewWindow = false;
                   }
                   
                   if (showInNewWindow == true) {
                       window.open(DETAIL_MAP_PAGE_URL + "?storeId=" + storeId, "_self");
                   }
                   else {
                       showOpeningHours(storeId, null);
                   }
                  
               }
          ); 
}


function removeAllMarkers() {
    if (gMap != null) {

        if (infowindow != null) {
            infowindow.close();
        }

        if (directionsDisplay != null) {
            directionsDisplay.setMap(null);
        }
        gMap.clearMarkers(); // clearMarkers
    }
}
