var localSearch = new GlocalSearch();
var args = new Array();
function setCoordinates() {
	if ($('postcodeInput')) {
		if ($defined($('postcodeInput').value) && $('postcodeInput').value.trim() != "") {
			args['postcode'] = $('postcodeInput').value;
			if($('countryId').selectedIndex>0)
				args['countryName'] = $('countryId').options[$('countryId').selectedIndex].text;
			else
				args['countryName'] = "";
			usePointFromPostcode(function (lat,lng) {
					$('latitude').value = lat;
					$('longitude').value = lng;
					document.forms[0].submit();
			}, args);
		} else {
			$('latitude').value = "";
			$('longitude').value = "";
			document.forms[0].submit();
		}
	} else {
		document.forms[0].submit();
	}	
}



function usePointFromPostcode(callbackFunction, args) {
	var postcode = args['postcode'];
	var countryName = $defined(args['countryName'])?args['countryName']:'';
	var lat=0;
	var lng=0;
	localSearch.setSearchCompleteCallback(null, 
		function(postcode) {

			if (localSearch.results[0])
			{		
				lat = localSearch.results[0].lat;
				lng = localSearch.results[0].lng;
			}else{
				lat = "";
				lng = "";
			}
			callbackFunction(lat,lng);

			},[args['postcode']]);	
	localSearch.execute(postcode + " , "+countryName);
}

function setPersonCoordinatesByNumber(id, finishFunction){
	if(!$defined(finishFunction)) finishFunction = Class.empty;
	if ($('postcodeInput'+id)) {
		if ($('postcodeInput'+id).value.trim() != "") {
			args['postcode'] = $('postcodeInput'+id).value;
			if($('personForm'+id+'.countryId').selectedIndex>0)
				args['countryName'] = $('personForm'+id+'.countryId').options[$('personForm'+id+'.countryId').selectedIndex].text;
			else
				args['countryName'] = "";
			usePointFromPostcode(function (lat,lng) {
					$('personForm'+id+'.latitude').value = lat;
					$('personForm'+id+'.longitude').value = lng;
					finishFunction();
			}, args);
		} else {
			$('personForm'+id+'.latitude').value = "";
			$('personForm'+id+'.longitude').value = "";
			finishFunction();
		}
	} else {
		finishFunction();
	}
	
}

function setPersonCoordinates() {
	setPersonCoordinatesByNumber(1,
			function() { setPersonCoordinatesByNumber(2, function(){ document.forms[0].submit() })
			}
	);
	
}

