﻿/// <reference path="jquery-1.3.2-vsdoc2.js"/>
var map = null;
var markers = new Array();
var infowindow = null;
var locationObjects = null;
var latlngUser;
var firstReset = false;
var markerBounds = null;
var markerArray = [];
var myOptions = null;


rad = function(x) { return x * Math.PI / 180; }
distHaversine = function(p1, p2) {
  var R = 6371; // earth's mean radius in km
  var dLat = rad(p2.lat() - p1.lat());
  var dLong = rad(p2.lng() - p1.lng());
  var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) * Math.sin(dLong / 2) * Math.sin(dLong / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c;
  return d.toFixed(3);
}

function initialize() {

  var stylez = [
  {
    featureType: "water",
    elementType: "all",
    stylers: [
      { visibility: "on" },
      { lightness: 100 }
    ]
  }, {
    featureType: "administrative",
    elementType: "all",
    stylers: [
      { lightness: -4 },
      { visibility: "off" }
    ]
  }, {
    featureType: "landscape",
    elementType: "all",
    stylers: [
      { hue: "#a55393" },
      { saturation: 10 },
      { lightness: -48 }
    ]
  }
]
  
  
  
      myOptions = {
        mapTypeControlOptions: {
        mapTypeIds: [google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.ROADMAP,google.maps.MapTypeId.TERRAIN, 'YouthNet.'],
          style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
          position: google.maps.ControlPosition.TOP

        },
        zoom: 4,
        //center: latlngUser,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };


      map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

      var styledMapOptions = {
      name: "YouthNet."
      }

      var jayzMapType = new google.maps.StyledMapType(
          stylez, styledMapOptions);

      map.mapTypes.set('YouthNet.', jayzMapType);
      map.setMapTypeId('YouthNet.');
  
  markerBounds = new google.maps.LatLngBounds();
  infowindow = new google.maps.InfoWindow();

  google.maps.event.addListener(map, "click", function() {
    infowindow.close();
  });

  var distanceBetweenOldAndNewLocation = null; //GetDistance();

  if (distanceBetweenOldAndNewLocation != null && distanceBetweenOldAndNewLocation >= 100) {

    var oldLatLng = GetOldLocation();
    if (oldLatLng == null)
      return null;

    var newLatLng = GetNewLocation();
    if (newLatLng == null)
      return null;
    var marker = null;

    var contentString = "your old location";
    makeMarkerAndInfoWindow({
      latLng: oldLatLng,
      content: contentString,
      title: "old location",
      type: "person_oldlocation",
      maxWidth: 20,
      openWindow: false
    });

    contentString = "<a href='#' onclick='UpdateCurrentUserPosition()'>Click here to update your position</a><br/><a href='#' onclick='CancelUpdateCurrentUserPosition()'>Cancel update your position</a>";
    makeMarkerAndInfoWindow({
      latLng: newLatLng,
      content: contentString,
      title: "new location",
      type: "person_newlocation",
      maxWidth: 20,
      openWindow: true
    });
    

    map.fitBounds(markerBounds);
    return;
  }
  //var newLatLng = GetNewLocation();
  //markerBounds.extend(newLatLng);
  
  GetLocationObjects();  
}

function CancelUpdateCurrentUserPosition() {
  RemoveCurrentUserMarkersAndAddLocationObjects();
  return false;
}

function RemoveCurrentUserMarkersAndAddLocationObjects() {
  infowindow.close();
  for (var i = 0; i < markerArray.length; i++) {
    markerArray[i].setVisible(false);
  }
  GetLocationObjects();
  return false;
}


function UpdateCurrentUserPosition() {
  if (google.loader.ClientLocation) {
    var currentUserPositionData = google.loader.ClientLocation.latitude + ',' + google.loader.ClientLocation.longitude + ',' + $("[id$='_hfCurrentUser']").val();
    GoogleMapService.IGoogleMapService.UpdateCurrentUserPosition(currentUserPositionData,
                function(result, eventArgs) {
                  RemoveCurrentUserMarkersAndAddLocationObjects();
                }
                , FailedCallback);
  }
}


function makeMarkerAndInfoWindow(options) {
  var marker = makeMarker({
    latLng: options.latLng,
    type: options.type,
    title: options.title
  });

  google.maps.event.addListener(marker, "click", function() {
    infowindow.setOptions(options);
    infowindow.open(map, marker);
  });
  if (options.openWindow) {
    infowindow.setOptions(options);
    infowindow.open(map, marker);
  }
  markerBounds.extend(options.latLng);
  markerArray.push(marker);
  return marker;
}



function makeMarker(options) {

  var iconWidth = GetIconWidth(options.type);
  var shadowWidth = GetShadowWidth(options.type);
  var iconAnchorX = GetIconAnchorX(options.type);

  var icon = new google.maps.MarkerImage(GetIconUrl(options.type),
  new google.maps.Size(iconWidth, 32),
  new google.maps.Point(0, 0),
  new google.maps.Point(iconAnchorX, 32));

  var shadow = null;
  //var shadow = new google.maps.MarkerImage(GetShadowUrl(options.type),
  //new google.maps.Size(shadowWidth, 32),
  //new google.maps.Point(0, 0),
  //new google.maps.Point(0, 32));

  var shape = { coord: [iconAnchorX, 1, iconAnchorX, 30, iconWidth - iconAnchorX, 30, iconWidth - iconAnchorX, 1], type: 'poly' };

  var marker = new google.maps.Marker({
    position: options.latLng,
    map: map,
    shadow: shadow,
    icon: icon,
    shape: shape,
    title: options.title,
    zIndex: 1// afhankelijk van type
  });
  return marker;
}    

// Retrieves all LocationObjects from the WebService
function GetLocationObjects() {

  var parentLocationObject = $("[id$='_hfParentLocationObject']");
  var encodedKey = parentLocationObject.val();
  if (encodedKey != '') {

    GoogleMapService.IGoogleMapService.GetPositionalDataByKey(encodedKey
        , GetDataSucceededCallBack
        , FailedCallback);

    var divFilter = $("#divFilter").hide();

  } else {

  GoogleMapService.IGoogleMapService.GetPositionalData(GetDataSucceededCallBack, FailedCallback);
  

    var divFilter = $("#divFilter").show();
  }
}



function GetDataSucceededCallBack(result) {
  locationObjects = eval(result);
  for (var i = 0; i < locationObjects.length; i++) {
    AddObjectMarker(locationObjects[i], i);
  }

  map.fitBounds(markerBounds);
  if (map.zoom > 5) {
    map.setZoom(5);
  }
}

function GetOldLocation() {

  var latLngCurrentUser = $("[id$='_hfLatLngCurrentUser']");
  if (latLngCurrentUser.length == 0 || latLngCurrentUser.val() == "" || !latLngCurrentUser.val().indexOf(',') == -1)
    return null;

  var sValue = latLngCurrentUser.val().split(',');
  if (sValue.length != 2)
    return null;

  return new google.maps.LatLng(sValue[0], sValue[1]);
}

function GetNewLocation() {

  if (!google.loader.ClientLocation)
    return null;

  return new google.maps.LatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
}

function GetDistance() {

  var oldLatLng = GetOldLocation();
  if (oldLatLng == null)
    return null;

  var newLatLng = GetNewLocation();
  if (newLatLng == null)
    return null;

  return distHaversine(newLatLng, oldLatLng);
}



function AddObjectMarker(locationObject, index) { 

  var latLng = new google.maps.LatLng(locationObject.Lat, locationObject.Long);

  var marker = makeMarker({
    latLng: latLng,
    type: locationObject.Type,
    title: locationObject.Title
  });
  
  var jSonObject = {
    "LocationObject": locationObject,
    "Marker": marker
  }

  markers[index] = jSonObject;
  markerBounds.extend(latLng);

  google.maps.event.addListener(marker, "click",
        function() {
          var jSonObjects = jQuery.grep(markers, function(n) {
            return (n.Marker == marker);
          });

          if (jSonObjects.length == 1) {

            var locationObject = jSonObjects[0].LocationObject;
            GoogleMapService.IGoogleMapService.GetObjectInformation(locationObject,
                function(result, eventArgs) {
                  var io = eval(result);

                  var contentString = "<a href='" + io.Key + "'>" + io.Title + "</a></b><br /><p>" + io.Information + "</p>";
                  //var contentString = "<a href='Redirect.aspx?key=" + io.Key + "'>" + io.Title + "</a></b><br /><p>" + io.Information + "</p>";
                  
                  infowindow.setContent(contentString);
                  infowindow.setOptions(
                  {
                    content: contentString,
                    maxWidth: 20
                  });
                  infowindow.open(map, marker);
                }
                , FailedCallback);
          }
        }
    );
}

// Retrieves an Image Location
function GetIconUrl(type) {
  var markerDirectory = $("[id$='_hfMarkerDirectory']").val()
  return markerDirectory + type + "-icon.png";
}

function GetShadowWidth(type) {
  switch (type) {
    case "organisation":
      return 42;
      break;
    case "project":
      return 38;
      break;
    case "vacancy":
      return 42;
      break;
    case "event":
      return 42;
      break;
    case "person":
    case "person_level1":
    case "person_level2":
    case "person_oldlocation":
    case "person_newlocation":
      return 45;
      break;
      break;
  }
}

function GetIconWidth(type) {
    switch (type) {
      case "organisation":
        return 29;
        break;
      case "project":
        return 26;
        break;
      case "event":
      case "vacancy":
        return 29;
        break;
      case "person":
      case "person_level1":
      case "person_level2":
        return 32;
        break;
      case "person_oldlocation":
      case "person_newlocation":
        return 84;
        break;
    }
  }

  function GetIconAnchorX(type) {
    switch (type) {
      case "organisation":
      case "project":
      case "event":
      case "vacancy":
        return 0;
        break;
      case "person":
      case "person_level1":
      case "person_level2":
        return 0;
        break;
        break;
      case "person_oldlocation":
      case "person_newlocation":
        return 27;
        break;
    }
  }
  


function GetShadowUrl(type) {
  var markerDirectory = $("[id$='_hfMarkerDirectory']").val()
  return markerDirectory + type + "-shadow.png";
}

function SetInformationBalloon() {

}



function Filter() {

  // Retrieve the filtervalues
  var title = $('#txtSearchGoogleMaps').val();
   
  var visibleMarkers = new Array(); 


 if ($('#chbOrganisation').attr('checked')) {
   visibleMarkers = $.merge(visibleMarkers, jQuery.grep(markers, function(n) {
      return (n.LocationObject.Type.toLowerCase() == $('#chbOrganisation').val());
    }));
  }
  
  if ($('#chbProject').attr('checked')) {
    visibleMarkers = $.merge(visibleMarkers, jQuery.grep(markers, function(n) {
      return (n.LocationObject.Type.toLowerCase() == $('#chbProject').val());
    }));
  }

  if ($("[id$=_chbPerson_Level1]").attr('checked')) {
    visibleMarkers = $.merge(visibleMarkers, jQuery.grep(markers, function(n) {
    return (n.LocationObject.Type.toLowerCase() == $("[id$=_chbPerson_Level1]").val());
    }));
  }

  if ($('#chbPerson_Level2').attr('checked')) {
    visibleMarkers = $.merge(visibleMarkers, jQuery.grep(markers, function(n) {
    return (n.LocationObject.Type.toLowerCase() == $('#chbPerson_Level2').val());
    }));
  }

  if ($('#chbVacancy').attr('checked')) {
    visibleMarkers = $.merge(visibleMarkers, jQuery.grep(markers, function(n) {
    return (n.LocationObject.Type.toLowerCase() == $('#chbVacancy').val());
    }));
  }


  if ($('#chbEvent').attr('checked')) {
    visibleMarkers = $.merge(visibleMarkers, jQuery.grep(markers, function(n) {
    return (n.LocationObject.Type.toLowerCase() == $('#chbEvent').val());
    }));
  }

  
  if (title != "" && title != "search google maps") {
    visibleMarkers = jQuery.grep(visibleMarkers, function(n) {
       return (n.LocationObject.Title.toLowerCase().indexOf(title.toLowerCase()) != -1);
    });
  }


  for (var i = 0; i < markers.length; i++) {

    if ($.inArray(markers[i], visibleMarkers) > -1) {
      markers[i].Marker.setVisible(true);
    } else {
      markers[i].Marker.setVisible(false);
    }  
  }
}

function FailedCallback(error) {


}


