/*
 * Helper JS Library for Google Maps v3 API
 * Developed by Kman
 * http://www.kman.gr
 */
var map = null;
var aMapPoints = new Array();
var aMapProgress = 0; aMapCount = 0;
var aMarkerClusterer = null;
var aClusteredMarkers = [];
var aTmpMarker = null;
var aInfoWindow = null;

function initializeGMap(aTitle,aAddress,aThumb,aInfo) {
  geocoder = new google.maps.Geocoder();
  map = new google.maps.Map(document.getElementById("map_canvas"),{
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });
  if(aTitle!='') showAddress(aTitle, aAddress, aThumb, aInfo);
}

/*
 * Based on all LatLng points added in the "aMapPoints" array
 * this function calculates the map center and sets it to the 
 * relevant object
 */
function calcMapCenter(){
  var latlngbounds = new google.maps.LatLngBounds();
  for(var i=0; i<aMapPoints.length; i++)
    latlngbounds.extend(aMapPoints[i]);
  map.setCenter(latlngbounds.getCenter());
  if(aMapPoints.length==1){
    map.setZoom(16);
  }else
    map.fitBounds(latlngbounds); 
}

/*
 * This function creates a custom marker for our application
 */
function eatMarker(aTitle,address,aThumb,aInfo,aLocationPoint,aImagePath){
  aMapPoints.push(aLocationPoint);

  var marker = new google.maps.Marker({
      position: aLocationPoint,
      map: map,
      icon: aImagePath+'images/marker/image.png',
      title: aTitle
  });

  aHTML = '';
  if(aThumb!='') aHTML = "<div style=\"float:left;margin-right:5px;width:50px;text-align:center;\"><img src='"+aThumb+"' width='50' border='0'/>"+aInfo+"</div>";
  aHTML += "<div style=\"float:left;width:160px;\"><b>"+aTitle+"</b><br/>"+address.replace(/,/gi,"<br/>")+'</div>';
  marker.kmCustomContent = aHTML;

  if(!aInfoWindow) aInfoWindow = new google.maps.InfoWindow({ content: aHTML });

  google.maps.event.addListener(marker, 'click', function() {
    aInfoWindow.setContent(marker.kmCustomContent);
    aInfoWindow.open(map,marker);
  });

  return marker;
}

/*
 * This function uses geocoding to find the location for a given
 * address. If succesful then it creates a marker and recalculates
 * the map's center
 */
function showAddress(aTitle,address,aThumb,aInfo,aUseTmpMarker) {
  aResult = null;
  if(!geocoder) return aResult;
  geocoder.geocode(
    {'address': address},
    function(results, status) {
      if (status != google.maps.GeocoderStatus.OK) return aResult;
      aMapPoint = results[0].geometry.location;
      if(aUseTmpMarker){
        document.getElementById('mapLat').value = aMapPoint.lat();
        document.getElementById('mapLng').value = aMapPoint.lng();
        if(aTmpMarker){
          aTmpMarker.setPosition(aMapPoint);
          aMapPoints[0] = aMapPoint;
        }else
          aTmpMarker = eatMarker(aTitle,address,aThumb,aInfo,aMapPoint,'');
        aTmpMarker.setDraggable(true);
        aTmpMarker.position_changed = function(){ 
          aNewPos = this.getPosition();
          document.getElementById('mapLat').value = aNewPos.lat();
          document.getElementById('mapLng').value = aNewPos.lng();
        };
      }else
        eatMarker(aTitle,address,aThumb,aInfo,aMapPoint,'');
      calcMapCenter();
      return aResult;
    }
  );
}

/*
 * This function creates a marker using the specified geolocation
 * coordinates. In the end it recalculates the map's center
 */
function showAddressLoc(aTitle,aAddress,aThumb,aInfo,aLat,aLng){
  aLocationPoint = new google.maps.LatLng(aLat,aLng);
  eatMarker(aTitle,aAddress,aThumb,aInfo,aLocationPoint,'');
  calcMapCenter();
}

/*
 * This function initializes the Clusterer object
 */
function initClusterer(){
  aMarkerClusterer = new MarkerClusterer(map, aClusteredMarkers);
}

/*
 * This function is used to create a clustered set of markers.
 * It uses as an input the Coordinates of each marker.
 */
function clAddr(aTitle,address,aThumb,aInfo,aLat,aLng) {
  aLocationPoint = new google.maps.LatLng(aLat,aLng);
  var aMarker = eatMarker(aTitle,address,aThumb,aInfo,aLocationPoint,'');
  if(!aMarker) return;
  aClusteredMarkers.push(aMarker);
}

function getAddressCoords(aId, aAddress) {
  if(!geocoder) return;
  geocoder.geocode(
    {'address': aAddress},
    function(results, status) {
      if (status != google.maps.GeocoderStatus.OK) {
        aMapProgress++; 
        aMapPercentage = aMapProgress/aMapCount; 
        jQuery('#dvProgress').html( "Πρόοδος "+aMapProgress+" από "+aMapCount+" ["+aMapPercentage+"%]" );
        doNextMapRefreshStep();
        return;
      };
      aMapPoint = results[0].geometry.location;

      eatMarker("",aAddress,"","",aMapPoint,'../');
      if(aMapProgress%5==0) calcMapCenter();

      var req = jQuery.ajax({
        url:'ajaxResUpdate.php',
        data: { 'id':aId, 'lat':aMapPoint.lat(), 'lng':aMapPoint.lng() },
        success: function(response) {
          aMapProgress++; 
          aMapPercentage = aMapProgress/aMapCount; 
          jQuery('#dvProgress').html("Πρόοδος "+aMapProgress+" από "+aMapCount+" ["+aMapPercentage+"%]");
          doNextMapRefreshStep(); 
        }
      });
    }
  );
}

function doNextMapRefreshStep(){
  if(aMapCount==aMapProgress){
    jQuery('#dvProgress').html("Πρόοδος "+aMapProgress+" από "+aMapCount+" [100]");
    alert('Process Finished!');
    return;
  }
  var req = jQuery.ajax({
    url:'ajaxRes.php',
    data: { 'l':aMapProgress+",1" },
    success: function(response) { eval(response); }
  });
}

function startMapRefresh(aCount){
  aMapCount = aCount; aMapProgress = 0;
  jQuery('#dvProgress').html("Πρόοδος 0 από "+aMapCount+" [0]");
  doNextMapRefreshStep();
}

function positionMarker(aTitle, aAddress){
  showAddress(aTitle, aAddress, '', '', true);
}
