//Provides a simple replace function (like in vbscript)
// returns a new string with all occurances of char stripped out:
function replaceChr (str, replaceChar) {
	str = new String(str);
	var strArray = str.split(replaceChar);
	str = '';
	for (var i=0; i<strArray.length; i++) {
		str += strArray[i];	
	}
	return str;
}

/*
* function getCoords
*
* desc: For translating OS national grid refs
*       into national grid x / y coord pairs.
* Passed: String - gridref
* Returns: Object with x and y properties / String - error message.
*
* Author: Dotted Eyes 2003.
* Version: 1.0.0
*
*/

function getCoords (os) {

	var errorMsg = "";

	os = replaceChr(os," ");

	//alert(os);

	var refLength = os.length;
	var sq = (os.substring(0,2)).toUpperCase();

	//test the ref has an even number of characters:
	if (refLength/2 == Math.round(refLength/2)) {
		
		//test the first two characters are alpha and not "I":
		var alpha = true;
		for (i=0;i<2;i++) {
			if (sq.charCodeAt(i) > 64 && sq.charCodeAt(i) < 91 && sq.charCodeAt(i) != "73") {
				alpha = true;
			} else {
				alpha = false;
				errorMsg = errorMsg + "Illegal character found:" + Number(i+1) + " ";
				break;
			}
		}
		
		if (alpha) {

			//check the remaining characters are numeric:
			var numeric = true;
			for (i=2;i<(refLength);i++) {
				if (os.charCodeAt(i) > 47 && os.charCodeAt(i) < 58) {
					numeric = true;
				} else {
					numeric = false;
					errorMsg = errorMsg + "Illegal character found:" + Number(i+1) + " ";
					break;
				}
			}

			if (numeric) {

				if (refLength > 2) {
					var xc = os.substring(2, refLength/2+1); 
					var yc = os.substring(refLength-(refLength/2-1), refLength);
				} else {
					var xc = "0"; 
					var yc = "0";
				}
				
				var exp_ten = Math.pow(10,5-(refLength/2-1));
			
				var xval = Number(xc);
				var yval = Number(yc);
				
				var x = xval*exp_ten
				var y = yval*exp_ten
			
				//coordObj = test_chs(sq,x,y);
				var coordObj = test_chs(sq,x,y);
			
				return coordObj;
				
			}
	
		}
			
	} else {
	
			errorMsg = errorMsg + "Grid references must have an even number of characters. ";
	
	}
	
	return errorMsg;

}


//function used by getCoords:
function test_chs(sq, x, y) {

	var val = new Array();

   	val[0] = (sq.toUpperCase()).charCodeAt(0) - 65;
    	val[1] = (sq.toUpperCase()).charCodeAt(1) - 65;

	//Letter I is not used in national grid, so reduce later letters by one:
    	for (i=0;i<2;i++) {
		if (val[i] > 7) {
			val[i] = Number(val[i]) - 1;
		} else {
			val[i] = Number(val[i]);
		}
	}
	
	x = Number(x) + 100000 * ((5 * (val[0] % 5)) + (val[1] % 5) - 10);
	y = Number(y) + 100000 * (19 - (5 * Math.floor(val[0] / 5)) - Math.floor(val[1] / 5));

	var coordObj = new Object();
	
	coordObj.x = x;
	coordObj.y = y;
	
	return coordObj;

}
