var map = null;
var customInfoBox = null;
var pushpins = new Array();
var pushpins_index = 0;
var detail_index = new Array();
var details = new Array();


function addPushPin(lat, lng, mls_number, map_details) {
	pushpins[pushpins_index] = new Microsoft.Maps.Location(lat,lng);
	detail_index[pushpins_index] = mls_number;
	details[mls_number] = map_details;
	pushpins_index++;
}

function displayListingInfo(e) {
	var pushpin = e.target;
	var location = pushpin.getLocation();
	var infoboxOptions = {
							offset: { x: 0, y: 25},
							showCloseButton: true,
							width :300, 
							height :185
						}; 
	customInfobox.setOptions(infoboxOptions);
    renderInfobox(location, pushpin.getZIndex());
//	var infobox = new Microsoft.Maps.Infobox(location, infoboxOptions );
//	infobox.setHtmlContent('<div id="infoboxText" ><b id="infoboxTitle">myTitle</b><a class="close" href="#">x</a><a id="infoboxDescription">Description goes here</a></div>');
//	infobox.setHtmlContent('<h2>This is the description...</h2>');
// 	map.entities.push(infobox);
}

function renderInfobox(latlong, mls_number) {
	if (customInfobox != null) {
		//Define the layout contents in the infobox
		var html = [details[mls_number]];
		customInfobox.show(latlong, html.join(''));
	}
}

function loadMap(centerLat, centerLng, mapDiv, zoomLevel) {

	if(pushpins.length > 1) {
		var boundingBox = Microsoft.Maps.LocationRect.fromLocations(pushpins); 
		map = new Microsoft.Maps.Map(document.getElementById(mapDiv), 
			{
				credentials: 'An-NgrNU5IodQ9OAYixix5Q13CfB19YliuLC3doZ9NMyOgPtAIgiIwQgHPXD-qF8',
				bounds: boundingBox
		//		center:  new Microsoft.Maps.Location(centerLat, centerLng), 
		//		zoom: zoomLevel
			});
	} else {
		map = new Microsoft.Maps.Map(document.getElementById(mapDiv), 
			{
				credentials: 'An-NgrNU5IodQ9OAYixix5Q13CfB19YliuLC3doZ9NMyOgPtAIgiIwQgHPXD-qF8',
				center:  new Microsoft.Maps.Location(centerLat, centerLng), 
				zoom: zoomLevel
			});	
	}
    //Register and load the Custom Infobox Module
    Microsoft.Maps.registerModule("CustomInfoboxModule", "http://www.4114homes.com/lite/js/V7CustomInfobox.min.js");
    Microsoft.Maps.loadModule("CustomInfoboxModule", { callback: function () {
	   //Create an instance of the custom infobox control and set intial options
   		customInfobox = new CustomInfobox(map, { orientation: 1, color: '#ccc', arrowWidth: 20 });
	  }
	});

	for (var i = 0; i < pushpins.length; i++) {
		var pushpin = new Microsoft.Maps.Pushpin(pushpins[i], {zIndex : detail_index[i]});
		Microsoft.Maps.Events.addHandler(pushpin, 'click', displayListingInfo);  
		map.entities.push(pushpin); 
	}
}
