var markersArray = [];

$(document).ready(function() {
  $("#map").css({
		height: 800,
		width: 696
	});
	// var myLatLng = new google.maps.LatLng(14.0583240, 108.2771990);
	var myLatLng = new google.maps.LatLng(15.7712538, 107.0219634);
    MYMAP.init('#map', myLatLng, 6);
  
  $("#showcities").click(function(e){
	MYMAP.placeMarkers('markers3.xml');
  });  
  
  $("#clearmarkers").click(function(e){
	clearOverlays();
  }); 
});

 var MYMAP = {
  map: null,
  bounds: null
}

MYMAP.init = function(selector, latLng, zoom) {
  var myOptions = {
    zoom:zoom,
    center: latLng,
	mapTypeControl: true,
    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
    navigationControl: true,
    navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
	scaleControl: true,
	scaleControlOptions: {position: google.maps.ControlPosition.TOP},
    mapTypeId: google.maps.MapTypeId.TERRAIN
  }
  this.map = new google.maps.Map($(selector)[0], myOptions);
  this.bounds = new google.maps.LatLngBounds();
}

MYMAP.placeMarkers = function(filename) {
	$.get(filename, function(xml){
		$(xml).find("marker").each(function(){
			var name = $(this).find('name').text();
			var address = $(this).find('address').text();
			var image = $(this).find('icon').text();
			
			// create a new LatLng point for the marker
			var lat = $(this).find('lat').text();
			var lng = $(this).find('lng').text();
			var point = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
			
			// extend the bounds to include the new point
			MYMAP.bounds.extend(point);
			
			var marker = new google.maps.Marker({
				position: point,
				map: MYMAP.map,
				title: name,
				icon: image
			});
			markersArray.push(marker);
			
			var infoWindow = new google.maps.InfoWindow();
			var html='<strong>'+name+'</strong.><br />'+address+'<br /><a href="/about.html" target="_new">Details</a>';
			google.maps.event.addListener(marker, 'click', function() {
				infoWindow.setContent(html);
				infoWindow.open(MYMAP.map, marker);
			});
			MYMAP.map.fitBounds(MYMAP.bounds);
		});
	});
}

function clearOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
  }
}

