var codesLookup = new Object();
var disCodesLookup = new Object();

function initCodes() {
	doGetUrl({url: './lookup.txt', handleAs: 'text/plain', load: populateCodes});
}

function populateCodes(xmlhttp) {
	var txt = xmlhttp.responseText;
	var lines = txt.split('\n');
	for (var i = 0; i < lines.length; i++) {
		var tokens = lines[i].split(',');
		codesLookup[tokens[0]] = {id: tokens[1], name: tokens[2]};
		var dis = tokens[0].substring(0, 4)
		if (disCodesLookup[dis] != null) {
			disCodesLookup[dis].push(tokens[0]);
		}
		else {
			disCodesLookup[dis] = new Array(tokens[0]);
		}
		dis = tokens[0].substring(0, 3)
		if (disCodesLookup[dis] != null) {
			disCodesLookup[dis].push(tokens[0]);
		}
		else {
			disCodesLookup[dis] = new Array(tokens[0]);
		}
	}
}

function doPostcodeSearch() {
	var pc = window.prompt('Type your postcode in the box below, then click OK', '');
	if ((pc == null) || (pc == ''))
		return;
	var pcode = pc + '';
	while (pcode.indexOf(' ') >= 0) {
		pcode = pcode.replace(' ', '');
	}
	pcode = pcode.toUpperCase();
	var ward = codesLookup[pcode];
	if (ward == null) {
		var matching = '';
		if (pcode.length >= 4) {
			var sub1 = pcode.substring(0, 4);
			var codes = disCodesLookup[sub1];
			if (codes != null) {
				matching = '\n\nThe following postcodes match some or all of your text \'' + sub1 + '\': ' + codes.slice(0, Math.min(codes.length, 15)).join(', ') + (codes.length > 15 ? '..., ' + codes[codes.length - 1] : '');
			}
		}
		if ((pcode.length >= 3) && (matching == '')){
			var sub1 = pcode.substring(0, 3);
			var codes = disCodesLookup[sub1];
			if (codes != null) {
				matching = '\n\nThe following postcodes match some or all of your text \'' + sub1 + '\': ' + codes.slice(0, Math.min(codes.length, 15)).join(', ') + (codes.length > 15 ? '..., ' + codes[codes.length - 1] : '');
			}
		}
		alert('The system could not find a ward for postcode \'' + pc + '\'. Please try again.\n\nPostcodes should be in the format AA1 1AA and should contain at least 6 letters or numbers.' + matching);
	}
	else {
		var movie = thisMovie('instantAtlasReport');
		var ok = window.confirm('Postcode \'' + pc.toUpperCase() + '\' lies in ward \'' + ward.name + '\'. Click OK to zoom to that ward.');
		if (ok) {
			movie.zoomToMapFeature(ward.id);
		}
	}
}
