var lat = null;
var lng = null;
var map = null;
var geocoder = null;
var marker = null;

function obtener_posicion(){
	if(lat === '' && lng === '' && navigator.geolocation){
		navigator.geolocation.getCurrentPosition(initialize,function(){
			initialize(null);
		});
	}else{
		initialize(null);
	}
}

function initialize(position){
	geocoder = new google.maps.Geocoder();
	var cor = null, myOptions = null;
	if(lat !== '' && lng !== ''){
		cor = new google.maps.LatLng(lat,lng);
		myOptions = {
			center: cor,
			zoom: 17,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
	}else{
		if(position !== null && typeof position.coords.latitude !== 'undefined' && typeof position.coords.longitude !== 'undefined'){
			cor = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
		}else{
			cor = new google.maps.LatLng(-36.82392646931029,-73.05621839062496);
		}
		myOptions = {
			center: cor,
			zoom: 13,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
	}
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	marker = new google.maps.Marker({
		map: map,
		position: cor,
		draggable: true
	});
	google.maps.event.addListener(marker, 'dragend', function(){
		updatePosition(marker.getPosition());
	});
}

function updatePosition(cor){
	$('#lat').val(cor.lat());
	$('#long').val(cor.lng());
}

function codeAddress(){
	var address = document.getElementById("ubicacion").value;
	geocoder.geocode({'address':address},function(results, status) {
		if(status == google.maps.GeocoderStatus.OK){
			map.setCenter(results[0].geometry.location);
			map.setZoom(12);
			marker.setPosition(results[0].geometry.location);
			updatePosition(results[0].geometry.location);
			google.maps.event.addListener(marker, 'dragend', function(){
				updatePosition(marker.getPosition());
			});
		}else{
			alert("No podemos encontrar la direccion, error: " + status);
		}
	});
}

jQuery(document).ready(function($){
	lat = $('#lat').val();
	lng = $('#long').val();
	if($('#buscar_ubicacion').length > 0){
		$('#buscar_ubicacion').click(function(){
			codeAddress();
		});
	}
	obtener_posicion();
});