// Phil Whitehurst
// Javascript for test OS Map
// September 2009

var osmap;
var postcodeService = new OpenSpace.Postcode(); 
var osGaz = new OpenSpace.Gazetteer;
var mapPoint;
var postcode;
var marker;
function osinit()
{
//the osMap variable refers to a div element whose size we have set in the html body 
osMap = new OpenSpace.Map('map');

//set-up default symboliser
 var symbolizer = OpenLayers.Util.applyDefaults(
     { }, OpenLayers.Feature.Vector.style["default"]);
//and a new style map
 var styleMap = new OpenLayers.StyleMap(symbolizer);
//this is our custom styling
 lookup = {
           "CTY":
           {fillColor: "red",
            fillOpacity: 0.0,
            strokeColor: "blue",
            strokeWidth: 6,
            strokeOpacity: 0.8}
           };
//add rules to the style map
 styleMap.addUniqueValueRules("default", "AREA_CODE", lookup);
// Add County Boundary
var options = {strategies: [new OpenSpace.Strategy.BBOX()],
                area_code: ["CTY" ],
				styleMap: styleMap
                            };
boundaryLayer = new OpenSpace.Layer.Boundary("Boundaries", options);
osMap.addLayer(boundaryLayer);

// get latlong from os grid reference
// Check if querystring with gridref
var params = Spry.Utils.getLocationParamsAsObject();
var gridref = params.gridref;

//set centre of map, place of marker, and zoom level 
if (!gridref) 
{
	pos = NGR2NE_wtp('TL1969007696')
	//specify the html content for the popup and its size
     var content = '<img src="Images/Core/HMCTitleBar.jpg" width="250" /><p>Three Horseshoes Pub, Smallford, St Albans, AL4 0HP</p>';
	 content += '<p>From 8.30pm on 1st and 3rd Tuesday of each month</p>';
}
else
{
	pos = NGR2NE_wtp(gridref);
	var content = "<h1>" + gridref + "</h1>";
}
osMap.setCenter(pos, 8); 
//add the marker to the map - null means no custom icon
var popUpSize = new OpenLayers.Size(310, 210);
osMap.clearMarkers();
osMap.openInfoWindow(null, pos, content, popUpSize );




// register event to capture mouseclick and show coords
var gridProjection = new OpenSpace.GridProjection();
osMap.events.register("click", osMap, function(e) {
var pt = osMap.getLonLatFromViewPortPx(e.xy);
var east = pt.lon;
var north = pt.lat;

var ngr = NE2NGR_wtp( east,  north)

var regex = /\s/g;
ngr = ngr.replace(regex,'');
Spry.$$('#maplink')[0].value = "http://www.thehmc.co.uk/osmap.html?gridref=" + ngr;

//specify the html content for the popup and its size
    var content = '<h1>' + ngr + '</h1>';
    var popUpSize = new OpenLayers.Size(300, 200)
    //add the marker to the map - null means no custom icon
	osMap.clearMarkers();
    marker = osMap.createMarker(pt, null, content, popUpSize );

});



}

//convert northing and easting to letter and number grid system
function NE2NGR_wtp( east,  north)
{
east = parseInt(east,10) ;
north = parseInt(north,10);
var eX = east / 500000;
var nX = north / 500000;
var tmp = Math.floor(eX) - 5.0 * Math.floor(nX) + 17.0; 
nX = 5 * (nX - Math.floor(nX));
eX = 20 - 5.0 * Math.floor(nX) + Math.floor(5.0 * (eX - Math.floor(eX)));
if (eX > 7.5) eX = eX + 1; // I is not used
if (tmp > 7.5) tmp = tmp + 1; // I is not used

var eing = east - (Math.floor(east / 100000)*100000);
var ning = north - (Math.floor(north / 100000)*100000);
var estr = eing.toFixed(0);
var nstr = ning.toFixed(0);
while(estr.length < 5)
	estr = "0" + estr;
while(nstr.length < 5)
	nstr = "0" + nstr;

var ngr = String.fromCharCode(tmp + 65) + 
          String.fromCharCode(eX + 65) + 
          " " + estr + " " + nstr;
return ngr;
}


//convert northing and easting to letter and number grid system, 4 figures
function NE2NGR_wtp4( east,  north)
{
east = parseInt(east/10,10)*10;
north = parseInt(north/10,10)*10;
var eX = east / 500000;
var nX = north / 500000;
var tmp = Math.floor(eX) - 5.0 * Math.floor(nX) + 17.0; 
nX = 5 * (nX - Math.floor(nX));
eX = 20 - 5.0 * Math.floor(nX) + Math.floor(5.0 * (eX - Math.floor(eX)));
if (eX > 7.5) eX = eX + 1; // I is not used
if (tmp > 7.5) tmp = tmp + 1; // I is not used

var eing = east - (Math.floor(east / 100000)*100000);
var ning = north - (Math.floor(north / 100000)*100000);
var estr = (eing/10.0).toFixed(0);
var nstr = (ning/10.0).toFixed(0);
while(estr.length < 4)
	estr = "0" + estr;
while(nstr.length < 4)
	nstr = "0" + nstr;

var ngr = String.fromCharCode(tmp + 65) + 
          String.fromCharCode(eX + 65) + 
          " " + estr + " " + nstr;
return ngr;
}




function NGR2NE_wtp(ngr){
var e;
var n;

ngr = ngr.toUpperCase(ngr);

var bits = ngr.split(' ');
ngr = "";
for(var i=0;i<bits.length;i++)
    ngr+=bits[i];

var c = ngr.charAt(0);
if (c =='S'){ 
    e = 0;
    n = 0;
    }
else if (c == 'T'){
    e = 500000;
    n = 0;
    }
else if (c == 'N'){ 
    n = 500000;
    e = 0;
    }
else if (c == 'O'){
    n = 500000;
    e = 500000;
    }
else if(c == 'H'){
    n = 1000000;
    e = 0;
    }
else 
    return null;
    
c = ngr.charAt(1);
if(c == 'I')
    return null;
    
c = ngr.charCodeAt(1) - 65;
if(c > 8)
    c -= 1;
e += (c % 5) * 100000;
n += (4 - Math.floor(c/5)) * 100000;

c = ngr.substr(2);
if ((c.length%2) == 1) 
    return null;
if (c.length > 10) 
    return null;

try{
    var s = c.substr(0,c.length/2);
    while(s.length < 5)
        s += '0';
    e += parseInt(s,10); 
    if(isNaN(e))
        return null; 
    
    s = c.substr(c.length/2);
    while(s.length < 5)
        s += '0';
    n += parseInt(s,10); 
    if(isNaN(n))
        return null;
        
    return new OpenSpace.MapPoint(e,n);
}
catch (ex)
{
    return null;
}

}


function centre()
{

//set centre of map and zoom level 
gridref = Spry.$('gridref').value;
Spry.$$('#maplink')[0].value = "http://www.thehmc.co.uk/osmap.html?gridref=" + gridref;
eastnorth = NGR2NE_wtp(gridref);
if (eastnorth)
{
osMap.setCenter(eastnorth, 7);

//specify the html content for the popup and its size
var content = '<h1>' + gridref + '</h1>';
var popUpSize = new OpenLayers.Size(300, 200)
//add the marker to the map - null means no custom icon
 osMap.clearMarkers();
 marker = osMap.createMarker(eastnorth, null, content, popUpSize );


}
return false;
}
function postcentre()
{
postcode = 	Spry.$('postcode').value.toUpperCase();
postcodeService.getLonLat(postcode, onpostResult);
return false;
 }
function onpostResult(mapPoint)
{
	
	if (mapPoint.length != 0) 
	{
	osMap.setCenter(mapPoint, 10);
	//specify the html content for the popup and its size
       var content = '<h1>' + postcode + '</h1>';
       var popUpSize = new OpenLayers.Size(300, 200)
    //add the marker to the map - null means no custom icon
	    osMap.clearMarkers();
        marker = osMap.createMarker(mapPoint, null, content, popUpSize );
	// now update link text  
	   var east = mapPoint.getEasting();
	   var north = mapPoint.getNorthing();
	   var ngr = NE2NGR_wtp( east,  north)
	   Spry.$$('#maplink')[0].value = "http://www.thehmc.co.uk/osmap.html?gridref=" + ngr;
	   
	}
}
function placecentre()
{
	
	var placeStr = Spry.$('placename').value.toUpperCase();
	if (placeStr.length = 3)
{
	
	var gazArray = osGaz.getLocations(placeStr, OngazResult);
}
}
function OngazResult(searchVal)
{
	dsPlacenames.setDataFromArray(searchVal);
	var myGaz = Spry.Widget.AutoSuggest('gazetter', 'placenames', 'dsPlacenames', 'name',{maxListItems:100});

	
}
function centreloc()
{
	var myRow = dsPlacenames.getCurrentRow();
	var location = myRow.location
	osMap.setCenter(location, 7);
	
	//specify the html content for the popup and its size
    var content = '<h1>' + myRow.name + '</h1>';
    var popUpSize = new OpenLayers.Size(300, 200)
    //add the marker to the map - null means no custom icon
	osMap.clearMarkers();
    marker = osMap.createMarker(location, null, content, popUpSize );
	
	// now update link text  
	   var east = location.getEasting();
	   var north = location.getNorthing();
	   var ngr = NE2NGR_wtp( east,  north)
	   Spry.$$('#maplink')[0].value = "http://www.thehmc.co.uk/osmap.html?gridref=" + ngr;
	

}
