
var baseIcon = new GIcon();
baseIcon.iconSize = new GSize(20, 20);
baseIcon.iconAnchor = new GPoint(20, 20);
baseIcon.infoWindowAnchor = new GPoint(10, 4);
baseIcon.infoShadowAnchor = new GPoint(0, 0);

var geocoder = new GClientGeocoder();
var index = 0;
var retryMax = 2;
var retryCount = 0;
var delay = 10;
var timerId = null;
var markers = [];

function geocodeAll() {	
	// Stop the timer if we have gotten them all
	if(index == app.points.length) {
		clearTimeout(timerId);
	}
	else {
		if(app.points[index].location.lat == null || app.points[index].location.long == null)
			geocoder.getLocations(app.points[index].location.fullAddress, app.placeMarker);
		else
			app.placeMarker({Status:{code:200}, Placemark:new Array({Point:{coordinates:new Array(app.points[index].location.long, app.points[index].location.lat)}})});
	}	
}

////////////////////////////////////////////
// Define App class and methods
////////////////////////////////////////////

function App() {
	this.lat = 37.54022177661216;
	this.long = -77.43365192291094;
	this.zoom = 8;
	
	this.areas = new Array(
		new AppArea("Chester"),
		new AppArea("Glen Allen"),
		new AppArea("Mechanicsville"),
		new AppArea("Midlothian"),
		new AppArea("Moseley")
	);
	
	this.points = new Array(
		new AppPoint(new AppLocation(1,"Coolwell", "8147 Travelers Rest Drive", "Mechanicsville", "VA", "23111", "CoolWell is a leisure lifestyle community for active adults featuring brick town homes with single story living and first-floor owner's suites. Choose from one of four home designs priced from the low $300's.", "From the $300s", "http://www.hhhunthomes.com/coolwell.htm", 37.62109806368172, -77.37250328063965)),
		new AppPoint(new AppLocation(2,"Greenbriar Woods", "4001 Overridge Drive", "Chester", "VA", "23831", "Greenbriar Woods homes, built by HHHunt Homes, are just right for YOU - affordable enough for first-time homebuyers and roomy enough for growing families. Many popular options such as finished basements, finished third floors, and morning rooms are also available.", "From the $300s", "http://www.hhhunthomes.com/Greenbriar%5FWoods/")),
		new AppPoint(new AppLocation(3,"Linden Pointe", "9209 Pornello Lane", "Glen Allen", "VA", "23059", "You've navigated your way to success and now you deserve the luxury of an HHHunt Home at Linden Pointe. A private gated community, you'll be welcomed to your all brick, low maintenance home with HHHunt Homes premier interior finish package.", "From the $300s", "http://www.hhhunthomes.com/lindenpointe.htm", 37.672130, -77.537090)),
		new AppPoint(new AppLocation(4,"Liberty Trace", "7700 Marshall Arch Drive", "Mechanicsville", "VA", "23111", "HHHunt Homes' newest community is in the heart of Mechanicsville. And, to make them even more attractive, they are very affordably priced in the mid $200's.", "From the $200s", "http://www.hhhunthomes.com/LibertyTrace/", 37.612130, -77.327310)),
		new AppPoint(new AppLocation(5,"Magnolia Green", "11607 Weeping Cherry Drive", "Moseley", "VA", "23120", "In the new community of Magnolia Green, you will find only the finest. And all of this in an area with great schools (the new Cosby High School included), healthcare, and shopping.", "From the $300s", "http://www.hhhunthomes.com/Magnolia%5FGreen/", 37.409540, -77.725350)),
		new AppPoint(new AppLocation(6,"Rutland", "8400 Combs Drive", "Mechanicsville", "VA", "23111", "A variety of floor plans will offer something for everyone, from first floor living to studies, gathering rooms and lofts. Rutland offers creative homes for every lifestyle all in a master planned community.", "From the $300s", "http://www.hhhunthomes.com/Rutland/index.htm", 37.65485, -77.39965)),
		new AppPoint(new AppLocation(7,"Stewart Village at Charter Colony", "1408 Colony Forest Court", "Midlothian", "VA", "23114", "Offering elegant first floor master retreats, two-story family rooms with fireplaces, spacious kitchens open to eating areas and great rooms, grand two-story entries and expansive basements, you'll find an abundance of choices.", "From the $300s", "http://www.hhhunthomes.com/stewartvillage_chartercolony.htm", 37.49466, -77.6710))
	);
}

App.prototype.load = function() {

	// Create map object
	this.map = new GMap2(document.getElementById("appmap"));
	this.map.removeMapType(G_HYBRID_MAP);
	this.map.setCenter(new GLatLng(this.lat, this.long), this.zoom);
	this.map.addControl(new GMapTypeControl());
	this.map.addControl(new GLargeMapControl());
		
	// Geocode address list
	timerId = setTimeout(geocodeAll, delay);
	
	// Load areas into a container
	for(var x=0; x < this.areas.length; x++) {
		var str = '<div id="' + this.areas[x].name.replace(" ","-") + '" class="areawrapper"><div class="title ' + this.areas[x].color + '"><div>' + this.areas[x].name + '</div></div><div class="body">';
		for(var y=0; y < this.points.length; y++) {
			if(this.points[y].location.city == this.areas[x].name)
				str += '<div id="' + y + '" class="area">' + this.points[y].location.getHtmlArea() + '</div>';
		}
		str += '<br clear="left" /><div class="footer">Close</div></div></div>';
		$("#apparea").append(str);
	}
	
	// Attach events to the title bars of each area wrapper
	$(".areawrapper > div.title").click(function(e) {
		$(".areawrapper > div.body").slideUp(25);
		$(this).next().slideDown(75);
	});
	
		// Attach events to the title bars of each area wrapper
	$(".areawrapper > div.body > div.footer").click(function(e) {
		$(this).parent().slideUp(25);
	});
	
	// Attach events to the title bars of each area wrapper
	$(".areawrapper > div.body > div.area").click(function(e) {
		app.locateMarker($(this).attr("id"));
	});
	
	// Bind click event to the map
	//GEvent.bind(this.map, "click", this, this.onMapClick);
}

App.prototype.locateMarker = function(index) {
	markers[index].openInfoWindowTabs(new Array(new GInfoWindowTab("Location", markers[index].location), new GInfoWindowTab("Description", markers[index].description)), {maxWidth:350});
}

App.prototype.placeMarker = function(response) {	
	
	if(retryCount == retryMax) {
		index++;
		retryCount = 0;
	}
	else if(response.Status.code == 602) {
		delay += 50;
		retryCount++;
	}
	else {
		if(response.Status.code == 200) {			
			point = new GLatLng(response.Placemark[0].Point.coordinates[1], response.Placemark[0].Point.coordinates[0]);
					
			// Pick the right color icon based on the city of the address
			var homeIcon = new GIcon(baseIcon, "http://wtvr.ameronixdev.com/images/home-"+(new AppArea(app.points[index].location.city)).color+".png");
			
			markerOptions = { icon:homeIcon, title:app.points[index].location.name };
			var marker = new GMarker(point, markerOptions);
			marker.location = app.points[index].location.getHtmlLocation();
			marker.description = app.points[index].location.getHtmlDescription();
			marker.city = app.points[index].location.city;
			marker.index = index;
			GEvent.addListener(marker, "click", function() {
				this.openInfoWindowTabs(new Array(new GInfoWindowTab("Location", marker.location), new GInfoWindowTab("Description", marker.description)), {maxWidth:300});
				app.loadPanel(this.city, this.index);
			});
			app.map.addOverlay(marker);
			markers.push(marker);
			
			index++;
		}
	}
	timerId = setTimeout(geocodeAll, delay);
}

App.prototype.unload = function() {
	GUnload();
}

App.prototype.loadPanel = function(city, index) {
	$(".areawrapper > div.body").slideUp(25);
	$("#" + city.replace(" ","-") + " > div.body").slideDown(75);
}

App.prototype.onMapClick = function() {}


////////////////////////////////////////////
// Define AppArea class and methods
////////////////////////////////////////////
function AppArea(name) {
	this.name = name;
	
	// Select color based on area name
	if(this.name == "Chester")
		this.color = "red";
	else if(this.name == "Glen Allen")
		this.color = "green";
	else if(this.name == "Mechanicsville")
		this.color = "orange";
	else if(this.name == "Midlothian")
		this.color = "blue";
	else if(this.name == "Moseley")
		this.color = "purple";
	else
		this.color = "purple";
}

////////////////////////////////////////////
// Define AppLocation class and methods
////////////////////////////////////////////
function AppLocation(id, name, address, city, state, zip, desc, price, url, lat, long) {
	this.id = id;
	this.name = name;
	this.address = address;
	this.city = city;
	this.state = state;
	this.zip = zip;
	this.desc = desc;
	this.price = price;
	this.url = url;
	this.lat = lat;
	this.long = long;
	
	this.fullAddress = this.address + ", " + this.city + ", " + this.state + " " + this.zip;
}

AppLocation.prototype.getHtmlLocation = function() {
	html  = '<div class="markerdisplay">';
	html += '  <div class="image"><img src="images/homes/' + this.id + '.png" width="100" height="100" border="0" /></div>';
	html += '  <div class="name">' + this.name + '</div>';
	html += '  <div class="address">' + this.address + '<br />' + this.city + ', ' + this.state + ' ' + this.zip + '</div>';
	html += '  <div class="website"><a href="' + this.url + '" target="_blank">Visit Website</a></div>';
	html += '</div>';	
	return html;
}

AppLocation.prototype.getHtmlArea = function() {
	html  = '<div class="name">' + this.name + '</div>';
	html += '<div class="address">' + this.address + '<br />' + this.city + ', ' + this.state + ' ' + this.zip + '</div>';	
	html += '<div class="price">' + this.price + '</div>';
	return html;
}

AppLocation.prototype.getHtmlDescription = function() {
	html  = '<div class="markerdisplay">';
	html += '  <div class="name">' + this.name + '</div>';
	html += '  <div class="description">' + this.desc + '</div>';
	html += '</div>';	
	return html;
}

////////////////////////////////////////////
// Define AppPoint class and methods
////////////////////////////////////////////
//
// When instantiating a new AppPoint we will attempt to locate the lat and long by the address.
// If lat and long are present we will skip this call, if the neighborhood is not found then
// the point will be hidden
//
////////////////////////////////////////////
function AppPoint(location) {
	this.location = location;
}