//
// Searches Ordnance Survey Gazetteer
// Returns a list of hyperlinks to maps centred on the found locations
// by Bob Osola 
//

// set event handlers
addEvent(window,"load",init);
function init() {  	
	document.getElementById('btnSearch').onclick = queryGaz;
	document.getElementById('txtSearch').onkeydown = trapEnterKey;
	document.getElementById('searchResults').onclick = hideMe;
}  

function queryGaz(){

	// query the OS gazetteer with the user's search string

	var strSearch = document.getElementById('txtSearch').value;

	if (strSearch.indexOf('*') > -1) {
		alert('Sorry, wildcards are not allowed. Use a partial word instead.')
	}
	else{
		if (strSearch.length < 3 ){
			alert('Search word must be at least three characters long.');
		}
		else {
			var gaz = new OpenSpace.Gazetteer();
			gaz.getLocations(strSearch, gazResults);
		}
	}
}

function trapEnterKey(e) {

	// runs the query if the Enter key was pressed

	if (!e) {
		var e = window.event
	}
	if (e.keyCode == 13){
		queryGaz();
	}
}

function hideMe(){
	this.style.display ='none'
}

function gazResults(gazEntry){

	// callback function to handle the returned data

	var sResult = '<div id=\'tableHolder\'><table border=\'0\'>'
				+ '<tr><th>No.</th><th>Name</th><th>County</th><th>Type</th></tr>';

	if (gazEntry == null || gazEntry.length == 0 ) {
		sResult += '<tr><td colspan=\'4\'>Nothing found.</td></tr>';
	}
	else{
		// got some entries to display
		for (var i = 0; i < gazEntry.length; i++ ){

			var strName = gazEntry[i].name;
                        var Xref=gazEntry[i].location.getEasting();
			var Yref=gazEntry[i].location.getNorthing();
			sResult += '<tr><td>' + (i + 1) + '</td>';
			sResult += '<td><form name="form1" method="post" action="Routes/Ridingmaps.php" ><input type="submit" name="Submit" value="'+strName+'"><input name="xref" value="'+Xref+'" type="hidden"><input name="yref" value="'+Yref+'" type="hidden"></form></td>';

			sResult += '<td>' + gazEntry[i].county + '</td>';

			// decapitalise (convert 'STRING' to 'String')
			var strType = gazEntry[i].type;
			strType = strType.substr(0,1) + strType.substr(1).toLowerCase();
			sResult += '<td>' + strType + '</td></tr>';
			
		}
	}
	sResult += '</table></div>';

	if (i) {
		sResult = '<p>Found ' + i + ' matches. '
		+ 'Click the name button to show the map or anywhere else in the box to close. Map will open in new window - Maximise window to full screen - close when done.</p>' + sResult;
	}
	else{
		sResult = '<p>No matches found. '
		+ 'Click anywhere in the box to close.</p>' + sResult;
	}

	// populate then show the results box
	var divResults = document.getElementById('searchResults');
	divResults.innerHTML = sResult;
	divResults.style.display = 'block';
}

// -------------------------------------------------

// Event handling utility functions written by Dean Edwards, 2005
// with input from Tino Zijdel, Matthias Miller, Diego Perini

// http://dean.edwards.name/weblog/2005/10/add-event/

function addEvent(element, type, handler) {
	if (element.addEventListener) {
		element.addEventListener(type, handler, false);
	} else {
		// assign each event handler a unique ID
		if (!handler.$$guid) handler.$$guid = addEvent.guid++;
		// create a hash table of event types for the element
		if (!element.events) element.events = {};
		// create a hash table of event handlers for each element/event pair
		var handlers = element.events[type];
		if (!handlers) {
			handlers = element.events[type] = {};
			// store the existing event handler (if there is one)
			if (element["on" + type]) {
				handlers[0] = element["on" + type];
			}
		}
		// store the event handler in the hash table
		handlers[handler.$$guid] = handler;
		// assign a global event handler to do all the work
		element["on" + type] = handleEvent;
	}
};
// a counter used to create unique IDs
addEvent.guid = 1;

function removeEvent(element, type, handler) {
	if (element.removeEventListener) {
		element.removeEventListener(type, handler, false);
	} else {
		// delete the event handler from the hash table
		if (element.events && element.events[type]) {
			delete element.events[type][handler.$$guid];
		}
	}
};

function handleEvent(event) {
	var returnValue = true;
	// grab the event object (IE uses a global event object)
	event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
	// get a reference to the hash table of event handlers
	var handlers = this.events[event.type];
	// execute each event handler
	for (var i in handlers) {
		this.$$handleEvent = handlers[i];
		if (this.$$handleEvent(event) === false) {
			returnValue = false;
		}
	}
	return returnValue;
};

function fixEvent(event) {
	// add W3C standard event methods
	event.preventDefault = fixEvent.preventDefault;
	event.stopPropagation = fixEvent.stopPropagation;
	return event;
};
fixEvent.preventDefault = function() {
	this.returnValue = false;
};
fixEvent.stopPropagation = function() {
	this.cancelBubble = true;
};


