/**
* Google maps setup and get directions
*/

google.load("maps", "2.x");

$(document).ready(function() {
	
	// Setup map on first #id found
	var map = new GMap2($("#map").get(0), { size: new GSize(927,320) } );
	
	// Remove controlls
	//map.removeMapType(G_NORMAL_MAP);
	//map.removeMapType(G_SATELLITE_MAP);
	//map.removeMapType(G_HYBRID_MAP);
	
	// Set LatLng and Zoom
	map.setCenter(new GLatLng(51.140687,-0.228213), 12);
	
	// Set controls
	//var mapControl = new GMapTypeControl();
	//map.addControl(mapControl);
	//map.addControl(new GSmallMapControl());
		
	// Pj Brown (call creatMarker() build directions
	var point = new GLatLng( 51.140687,-0.228213 );
	var pjBrown = createMarker(point,'pjBrown','<p><strong>PJ Brown Construction Ltd</strong></p><br><p style="line-height:1.4em;">Burlands, Charlwood Road,<br>Ifield Wood, Crawley RH11 0JZ</p><br>');
	map.addOverlay(pjBrown);
	
});


// Maps marker Directions
var gmarkers = [];
var htmls = [];
var to_htmls = [];
var from_htmls = [];
var i=0;

// A function to create the marker and set up the event window
function createMarker(point, name, html) {
	var marker = new GMarker(point);
	
	htmlOpen = '<div class="bubble">';
	htmlClose = '<br></div>';
	
	// The info window version with the "to here" form open
	to_htmls[i] = htmlOpen + html + '<p>Directions: <b>To here</b> - <a href="javascript:fromhere(' + i + ')">From here</a>' +
	   '<br><br><strong>Start address:</strong></p><form action="http://maps.google.com/maps" method="get" target="_blank">' +
	   '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
	   '<INPUT class="directionsBtn" value="" TYPE="SUBMIT">' +
	   '<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + 
			  // "(" + name + ")" + 
	   '"/>' + '<br>' + htmlClose;
	// The info window version with the "to here" form open
	from_htmls[i] = htmlOpen + html + '<p>Directions: <a href="javascript:tohere(' + i + ')">To here</a> - <b>From here</b>' +
	   '<br><br><strong>End address:</strong></p><form action="http://maps.google.com/maps" method="get"" target="_blank">' +
	   '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' +
	   '<INPUT class="directionsBtn" value="" TYPE="SUBMIT">' +
	   '<input type="hidden" name="saddr" value="' + point.lat() + ',' + point.lng() +
			  // "(" + name + ")" + 
	   '"/>' + '<br>' + htmlClose;
	// The inactive version of the direction info
	html = html + '<p>Directions: <a href="javascript:tohere('+i+')">To here</a> - <a href="javascript:fromhere('+i+')">From here</a><br></p>';
	
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(htmlOpen+html+htmlClose);
	});
	
	gmarkers[i] = marker;
	htmls[i] = html;
	i++;
	return marker;
}

// functions that open the directions forms
function tohere(i) {
	gmarkers[i].openInfoWindowHtml(to_htmls[i]);
}
function fromhere(i) {
	gmarkers[i].openInfoWindowHtml(from_htmls[i]);
}
