var marker = null;
//var wayPoint = null;
var mapGoogle = null;
var geocoder = null;
var zoomMap = 12;

  google.load("maps", "2");
  //google.load("elements", "1", {packages : ["localsearch"]});


  function updateMaps(typeClassified){
      if (mapGoogle == null){
        createMaps(typeClassified);
      }else{
        updateWayPoint(typeClassified);
      }
  }
  // Call this function when the page has been loaded
  function createMaps(typeClassified) {
    if(GBrowserIsCompatible()){
        mapGoogle = new google.maps.Map2(document.getElementById("map_canvas"));
        geocoder = new google.maps.ClientGeocoder();

        mapGoogle.addControl(new google.maps.LargeMapControl());
        mapGoogle.addControl(new google.maps.MapTypeControl());

//        var options = {
//            searchFormHint: 'Busque su dirección',
//            onSearchCompleteCallback: searchComplete
//        };
        //Se agrega componente para realizar busquedas dentro del mapa
        //mapGoogle.addControl(new google.elements.LocalSearch(options));
        var location = "";
        if (typeClassified == 'add'){
            location = $('#ClassifiedCityId :selected').text() + ", " + $('#ClassifiedStateId :selected').text() + ", " + $('#ClassifiedCountry').val();
        }else if(typeClassified == 'edit'){
            location = new google.maps.LatLng($('#ClassifiedLatitude').val(), $('#ClassifiedLongitude').val());
        }
        //Se ubica el punto en el mapa y se centra el mapa
        geocoder.getLatLng(location, function(tmpWayPoint){
            if(typeClassified == 'edit'){
                tmpWayPoint = location;
            }
            marker = new google.maps.Marker(tmpWayPoint, {draggable: true});
            marker.setPoint(tmpWayPoint);
            mapGoogle.setCenter(tmpWayPoint , zoomMap);
            mapGoogle.addOverlay(marker);
            
            marker.openInfoWindowHtml("<center>Arrastre la referencia<br /> a su nueva ubicación</center>")
            saveLatitudeLongitude(tmpWayPoint);

            GEvent.addListener(marker, "dragstart", function() {
                marker.closeInfoWindow();
            });

            GEvent.addListener(marker, "dragend", function(tmpWayPoint) {
                saveLatitudeLongitude(tmpWayPoint);
                marker.openInfoWindowHtml("<center>Arrastre la referencia<br /> a su nueva ubicación</center>")
            });

        });

        //Controlo si el marcador que estoy utilizando se encuentra dentro del área activa
        GEvent.addListener(mapGoogle, "dragend", function() {
            var newBounds = mapGoogle.getBounds();
            if(!newBounds.contains(marker.getLatLng())){               
				var tmpWayPoint = mapGoogle.getCenter();
                marker.setLatLng(tmpWayPoint);
                marker.openInfoWindowHtml("<center>Arrastre la referencia<br /> a su nueva ubicación</center>")
                saveLatitudeLongitude(tmpWayPoint);
            }
        });
    }
 }
// google.setOnLoadCallback(createMaps);

function updateWayPoint(typeClassified) {
    var location = "";
    if (typeClassified == 'add'){
        location = $('#ClassifiedCityId :selected').text() + ", " + $('#ClassifiedStateId :selected').text() + ", " + $('#ClassifiedCountry').val();
    }else if(typeClassified == 'edit'){
        location = $('#ClassifiedLatitude').val() + ", " + $('#ClassifiedLongitude').val();
    }
    //Obtengo la nueva ubicación en el mapa
    geocoder.getLatLng(location, function(tmpWayPoint){
    //Se centra el mapa en el punto y se guarda su ubicación
        mapGoogle.setCenter(tmpWayPoint, zoomMap);
        saveLatitudeLongitude(tmpWayPoint);
    //Se reubica el marcador en el mapa de manera centrada
        marker.setPoint(tmpWayPoint) ;
        marker.openInfoWindowHtml("<center>Arrastre la referencia<br /> a su nueva ubicación</center>");
    });
}

function searchComplete(a, response) {
  // Triggers after a user does a search
  console.debug(response.responseData.results[0]);
}


function saveLatitudeLongitude(tmpPoint){
    document.getElementById('ClassifiedLatitude').setAttribute("value", tmpPoint.lat());
    document.getElementById('ClassifiedLongitude').setAttribute("value",tmpPoint.lng());
}

function clearLatitudeLongitude(){
    document.getElementById('ClassifiedLatitude').setAttribute("value", "");
    document.getElementById('ClassifiedLongitude').setAttribute("value","");
    document.getElementById('ClassifiedMapsDescription').setAttribute("value","");
}

$().unload(function() {
   GUnload();
 });
