// JavaScript Document

var geocoder,latlng={},replyto,userid;

function gmaps_init () {
	geocoder = new GClientGeocoder();
};

function latlngfrommake (pc, id) {
	pc=pc.toUpperCase();
	if(!(pc.match(/^[A-Z]{1,2}[0-9]{1,2}[ ]{0,1}[0-9][A-Z]{2}$/) || pc.match(/^[A-Z]{1,2}[0-9][A-Z][ ]{0,1}[0-9][A-Z]{2}$/))) {
		alert(pc +' for id '+id+' is not a valid postcode format (5-7 alpha-numeric characters)');
		return false;
	}
	pc=pc.replace(" ","");
	geocoder.getLocations(pc+" GB",function(response2){
		if(response2.Status.code != G_GEO_SUCCESS) {
			if(response2.Status.code == G_GEO_UNKNOWN_ADDRESS) {
				alert('Sorry, Unable to lookup postcode .\nThe address does not exist, is badly formatted, or is a new address.');
			} else {
				alert('An error occured looking up the postcode');
			}
			latlng[0]=-1;
			latlng[1]=-1;
		}	else {
			latlng[0] = response2.Placemark[0].Point.coordinates[0];
			latlng[1] = response2.Placemark[0].Point.coordinates[1];
		}
		page_string = '/admin/postcode_make.php?update=1&id='+id+'&lat='+latlng[1]+'&long='+latlng[0];
		window.document.location.href=page_string;
	});
};

function latlngfrom (reply) {
	var pc = xGetElementById('postcode').value.toUpperCase();
	if(!(pc.match(/^[A-Z]{1,2}[0-9]{1,2}[ ]{0,1}[0-9][A-Z]{2}$/) || pc.match(/^[A-Z]{1,2}[0-9][A-Z][ ]{0,1}[0-9][A-Z]{2}$/))) {
		alert(pc +' is not a valid postcode format (5-7 alpha-numeric characters with an optional space)');
		return false;
	}
	pc=pc.replace(" ","");
	replyto=reply;
	geocoder.getLocations(pc+" GB",function(response){
		if(response.Status.code != G_GEO_SUCCESS) {
			if(response.Status.code == G_GEO_UNKNOWN_ADDRESS) {
				alert('Sorry, Unable to lookup postcode '+pc+'.\nThe address does not exist, is badly formatted, or is a new address.');
			} else {
				alert('An error occured looking up the postcode');
			}
			latlng[0]=-1;
			latlng[1]=-1;
		}	else {
			latlng[0] = response.Placemark[0].Point.coordinates[0];
			latlng[1] = response.Placemark[0].Point.coordinates[1];
		}
		if(replyto=='form') {
			xGetElementById('lat').value=latlng[1];
			xGetElementById('long').value=latlng[0];
		}
		if(replyto=='search') {
			page_string = '/postcode_search?lat='+latlng[1]+'&long='+latlng[0];
			window.document.location.href=page_string;
		}
	});
};

gmaps_init();

