var map;
var centreLatLng;
var bounds;
var zoom = 13;
var geocoder;
//var marker;
//var markerAddress;
//var markerLatLng;

function getGeoCoder(){
	var g = new GClientGeocoder();
	g.setBaseCountryCode('uk');
	return g;
}

function loadProfileGMap(containerID) {
	if (GBrowserIsCompatible() && document.getElementById(containerID)) {
		var mapdiv = document.getElementById(containerID);
		mapdiv.style.display = 'block';
		map = new GMap2(mapdiv);
		map.addControl(new GMapTypeControl());
		map.addControl(new GLargeMapControl());
		marker = false;
		GEvent.addListener(map,'click',function(overlay,latlng) {
			addMarkerOnClick(latlng);
		});
		bounds = new GLatLngBounds();
		geocoder = getGeoCoder();
	}
}

function loadOverviewGMap(containerID) {
	if (GBrowserIsCompatible() && document.getElementById(containerID)) {
	
		var mapTypes = G_DEFAULT_MAP_TYPES;
		for(var i = 0; i < mapTypes.length; i++){
			mapTypes[i].getMaximumResolution = function(latlng){ return 12;};
			mapTypes[i].getMinimumResolution = function(latlng){ return 2;};
		}

		var mapdiv = document.getElementById(containerID);
		map = new GMap2(mapdiv);
    map.addControl(new GMapTypeControl());
		map.addControl(new GLargeMapControl());
		bounds = new GLatLngBounds();
		geocoder = getGeoCoder();
	}
}

function autoSizeMapContainer(containerID) {
	var margin = 3;
	containerID = '#'+containerID
	var mapElem = jQuery(containerID);
	var mapParent = mapElem.parent();
	mapElem.css('width',(mapParent.width()-(margin*2))+'px');
	mapElem.css('margin-left',margin+'px');
	mapElem.css('margin-top',margin+'px');
	mapElem.css('height',(mapParent.height()-(margin*2))+'px');
}

function addMarkerOnClick(latlng) {
	if (latlng) {
		if (!marker || !map.getBounds().containsLatLng(marker.getLatLng())) {
			map.clearOverlays();
			marker = new GMarker(latlng, {draggable: true, bouncy: false});
			map.addOverlay(marker);
			GEvent.addListener(marker,'dragend', function(dropLatLng) {
				handleMarkerDrop(marker, dropLatLng);
			});
			handleMarkerDrop(marker,latlng);
		}
	}
}

//TODO marker does not update lat and lng
function handleMarkerDrop(marker,dropLatLng) {
	geocoder.getLocations(dropLatLng, function(response){
		if (response.Status.code == 200) {
			markerLatLng = dropLatLng;
			//TODO fix this to display less specific
			addressDetails = response.Placemark[0].AddressDetails
			markerAddress = addressDetails.Country.AdministrativeArea.AdministrativeAreaName + ', ' + addressDetails.Country.CountryName;
			marker.openInfoWindowHtml('<p id=\'dragInfo\'>'+markerAddress+'</p><a id=\'set-location\' href=\'#\'>Click to confirm location</a>');
		}
	});
}

function showAddress(address) {
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        //alert(address + ' not found');
      } else {
        map.setCenter(point, zoom);
        map.clearOverlays();
        marker = new GMarker(point, {draggable: true, bouncy: false});
        map.addOverlay(marker);
				handleMarkerDrop(marker, point);
        GEvent.addListener(marker,'dragend', function(dropLatLng) {
        	handleMarkerDrop(marker, dropLatLng);
        });
      }
    }
  );
}

function showLatLng(lat,lng){
	point = new GLatLng(lat,lng);
	map.setCenter(point, zoom);
	map.clearOverlays();
	marker = new GMarker(point, {draggable: true, bouncy: false});
	map.addOverlay(marker);
	handleMarkerDrop(marker, point);
	GEvent.addListener(marker,'dragend', function(dropLatLng) {
	  handleMarkerDrop(marker, dropLatLng);
	});
}

function getCurrentPledgeLocation() {
	if (jQuery('#curr-pledge-location').val().length > 0) {
		return jQuery('#curr-pledge-location').val();
	}
	return false;
}

function useDefaultLocation(){
	centreLatLng = new GLatLng(0,0);
	map.setCenter(centreLatLng,0);
}

function addMarkerForPost(post){
	if (post.lat != null && post.lat != undefined) {
  	marker = new GMarker(new GLatLng(post.lat, post.lng));
  	
  	if(post.heroine != '' && post.heroine != null && post.heroine != undefined){
    	GEvent.addListener(marker,'click',function(){
    	  markerHTML = '<p>'+post.heroine ;
    	  if(post.url != '') markerHTML += '<br /><a href="'+post.url+'" target="_blank">'+post.url+'</a>';
    	  markerHTML += '</p>';
        
    	  this.openInfoWindowHtml(markerHTML);
    	});
  	}else if(post.name != '' && post.name != null && post.name != undefined){
			GEvent.addListener(marker,'click',function(){
    	  markerHTML = '<p>'+ post.name + '</p>';
    	  this.openInfoWindowHtml(markerHTML);
    	});
		}
  	map.addOverlay(marker);
  }
}

var markers = [];
var currentListType;

function loadMarkers(list){
	if(currentListType != list && /all|heroine|author/.test(list) ){
		currentListType = list;
		map.clearOverlays();
		markers = [];
	}
	jQuery.ajax({
    url: '/wp-content/plugins/tp-pledge/locations.ajax.php?list=' + currentListType,
    cache: false,
		dataType: 'json',
    success: function(submissions) {			
			for(var i = 0;i < submissions.length; i++){
				sub = submissions[i];
				if(	typeof(markers[sub.uid]) == 'undefined'){
					markers[sub.uid] = sub;
					addMarkerForPost(markers[sub.uid]);
				}
			};
    }
  });
}

function initProfileMap(containerID) {

	var currentLoc = jQuery('#pledge-location').val();

	autoSizeMapContainer(containerID);
	loadProfileGMap(containerID);
	if (currentLoc.length > 0) {
		if (jQuery('#pledge-latitude').val().length > 0) {
		  showLatLng(jQuery('#pledge-latitude').val(), jQuery('#pledge-longitude').val());
		}else{
			showAddress(currentLoc);
		}
	} else {
		useDefaultLocation();
	}
}

function initOverviewMap(containerID) {
	autoSizeMapContainer(containerID);
	loadOverviewGMap(containerID);
	useDefaultLocation();
	
	loadMarkers('all');
	setInterval(loadMarkers,60000);
}

var drawMapTimeout;

function drawProfileMap(){
	if(map == undefined){
		jQuery('#pledge-profile-map-container').animate({
			width: '500px',
			height: '280px'
		},300,0,function(){
			initProfileMap('pledge-profile-map');
			showAddress(jQuery('#pledge-location').val());
			jQuery('#close-map').click(function(){
        jQuery('#pledge-profile-map-container').hide();
        return false;
      });
		});
	}else{
		showAddress(jQuery('#pledge-location').val());
	}

}

jQuery(document).ready(function(){
	if (jQuery('#pledge-overview-map').get().length > 0) {
		initOverviewMap('pledge-overview-map');
	}
	
	jQuery('#pledge-location').keyup( function(){
		clearTimeout(drawMapTimeout);
		drawMapTimeout = setTimeout(drawProfileMap,900);
  });

});

jQuery(window).unload(function(){
	GUnload();
});

jQuery(window).click(function(e) {
	if (e.target.id == 'set-location') {
		e.preventDefault();
		jQuery('#pledge-location').val(markerAddress);
		
		jQuery('#pledge-longitude').val(markerLatLng.lng());
		jQuery('#pledge-latitude').val(markerLatLng.lat());
		jQuery('#pledge-profile-map-container').hide();
		map.closeInfoWindow();
	}
});

	
