﻿if (!MiniMap) {
    alert("map point not set");
}
function ValidatePostcode(PC) {
	// parse the postcode string to see if it is in a valid format
	// i.e. AADDL SCC,
	// where:	AA is a 1 or 2 two letters Area code
	//			DD is a 1 or 2 digit code to specify the district
	//			L is 0 or 1 letters used in central London (e.g. EC1A district types)
	//			S is one digit sector code
	//			CC is two letters finishing the full postcode
	//

	var reg = /^([a-z]{1,2})(\d{1,2})[a-z]? \d[a-z]{2}$/ig;

	return reg.test(PC);
}

function GetPCsector(PC) {
	// extract the sector only, as Google maps API won't geocode full postcodes
	// Remember to ensure postcode is valid before calling this
	var Sector;
	var match;
	var reg = /^([a-z]{1,2})(\d{1,2})[a-z]? \d/ig;
	match = PC.match(reg);
	Sector = match[0];
	return Sector;
}

MiniMap.setmap =
    function() {
    	var map = new GMap2(document.getElementById("MiniMap"));
    	var geocoder = new GClientGeocoder();
    	if (map) {
    		// if no coordinates available, try to get some from the address
    		if (this.point.x != 0 && this.point.y != 0) {
    			var gpoint = new GLatLng(this.point.y, this.point.x);
    			map.setCenter(gpoint, 14);
    			marker = new GMarker(gpoint);
    			map.addOverlay(marker);
    		} else {
    		if (ValidatePostcode(this.Postcode)) {
    			// setup using postcode sector
    			geocoder.setBaseCountryCode("UK");
    			geocoder.getLatLng(GetPCsector(this.Postcode) + ',UK',
						function(latlng) {
							if (latlng) {
								map.setCenter(latlng, 14);
								marker = new GMarker(latlng);
								map.addControl(new GSmallMapControl(), G_ANCHOR_TOP_LEFT);
								map.addOverlay(marker);
							} // end if latlng
						} // end callback function
				);
    		} // end if ValidatePostcode
    		// now try to replace that with more specific version
    		geocoder.getLatLng(this.Address + ',' + this.Postcode + ',UK',
					function(latlng) {
						if (latlng) {
							map.setCenter(latlng, 14);
							marker = new GMarker(latlng);
							map.addControl(new GSmallMapControl(), G_ANCHOR_TOP_LEFT);
							map.addOverlay(marker);
						} // end if latlng
					} // end callback function
			);
    		}   // end if coords = 0
    	} //end if map 
    }
MiniMap.setmap();
