function get_cookie ( cookie_name )
{
  var results = document.cookie.match ( cookie_name + '=(.*?)(;|$)' );

  if ( results )
    return ( unescape ( results[1] ) );
  else
    return null;
}

function delete_cookie ( cookie_name )
{
  //alert (cookie_name);
  var cookie_date = new Date ( );  // current date & time
  cookie_date.setTime ( cookie_date.getTime() - 1 );
  document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
  //alert (cookie_name += "=; expires=" + cookie_date.toGMTString());
}

function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
  var cookie_string = name + "=" + escape ( value );

  if ( exp_y )
  {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }

  if ( path )
        cookie_string += "; path=" + escape ( path );

  if ( domain )
        cookie_string += "; domain=" + escape ( domain );
  
  if ( secure )
        cookie_string += "; secure";
  
  document.cookie = cookie_string;
}



function displaySearchMap()
{

<!-- WMS SCRIPT STARTS HERE -->

    /*
     * Call generic wms service for GoogleMaps v2
     * John Deck, UC Berkeley
     * Inspiration & Code from:
     *      Mike Williams http://www.econym.demon.co.uk/googlemaps2/ V2 Reference & custommap code
     *      Brian Flood http://www.spatialdatalogic.com/cs/blogs/brian_flood/archive/2005/07/11/39.aspx V1 WMS code
     *      Kyle Mulka http://blog.kylemulka.com/?p=287  V1 WMS code modifications
     *      http://search.cpan.org/src/RRWO/GPS-Lowrance-0.31/lib/Geo/Coordinates/MercatorMeters.pm
     * 		Modified by Chris Holmes, TOPP to work by default with GeoServer.
     *		Guilhem Vellut <guilhem.vellut@gmail.com> for more accurate Javascript Mercator Fxn
     *
     * Note this only works with gmaps v2.36 and above.  http://johndeck.blogspot.com
     * has scripts
     * that do the same for older gmaps versions - just change from 54004 to 41001.
     *
     * About:
     * This script provides an implementation of GTileLayer that works with WMS
     * services that provide epsg 41001 (Mercator).  This provides a reasonable
     * accuracy on overlays at most zoom levels.  It switches between Mercator
     * and Lat/Long at the myMercZoomLevel variable, defaulting to MERC_ZOOM_DEFAULT
     * of 5.  It also performs the calculation from a GPoint to the appropriate
     * BBOX to pass the WMS.  The overlays could be more accurate, and if you
     * figure out a way to make them so please contribute information back to
     * http://docs.codehaus.org/display/GEOSDOC/Google+Maps.  There is much
     * information at:
     * http://cfis.savagexi.com/articles/2006/05/03/google-maps-deconstructed
     *
     * Use:
     * This script is used by creating a new GTileLayer, setting the required
     * and any desired optional variables, and setting the functions here to
     * override the appropriate GTileLayer ones.
     *
     * At the very least you will need:
     * var myTileLayer= new GTileLayer(new GCopyrightCollection(""),1,17);
     *     myTileLayer.myBaseURL='http://yourserver.org/wms?'
     *     myTileLayer.myLayers='myLayerName';
     *     myTileLayer=CustomGetTileUrl
     *
     * After that you can override the format (myFormat), the level at
     * which the zoom switches (myMercZoomLevel), and the style (myStyles)
     * - be sure to put one style for each layer (both are separated by
     * commas).  You can also override the Opacity:
     *     myTileLayer.myOpacity=0.69
     *     myTileLayer.getOpacity=customOpacity
     *
     * Then you can overlay on google maps with something like:
     * var layer=[G_SATELLITE_MAP.getTileLayers()[0],tileCountry];
     * var custommap = new GMapType(layer, G_SATELLITE_MAP.getProjection(), "WMS");
     * var map = new GMap(document.getElementById("map"));
     *     map.addMapType(custommap);
     */

    var MAGIC_NUMBER=6356752.3142;
    var WGS84_SEMI_MAJOR_AXIS = 6378137.0;
    var WGS84_ECCENTRICITY = 0.0818191913108718138;

    var DEG2RAD=0.0174532922519943;
    var PI=3.14159267;

    //Default image format, used if none is specified
    var FORMAT_DEFAULT="image/png";

    //Google Maps Zoom level at which we switch from Mercator to Lat/Long.
    var MERC_ZOOM_DEFAULT = 15;
    function dd2MercMetersLng(p_lng) {
	    return WGS84_SEMI_MAJOR_AXIS * (p_lng*DEG2RAD);
    }

    function dd2MercMetersLat(p_lat) {
	    var lat_rad = p_lat * DEG2RAD;
	    return WGS84_SEMI_MAJOR_AXIS * Math.log(Math.tan((lat_rad + PI / 2) / 2) * Math.pow( ((1 - WGS84_ECCENTRICITY * Math.sin(lat_rad)) / (1 + WGS84_ECCENTRICITY * Math.sin(lat_rad))), (WGS84_ECCENTRICITY/2)));
    }

    CustomGetTileUrl=function(a,b,c) {
	    if (this.myMercZoomLevel == undefined) {
    	    this.myMercZoomLevel = MERC_ZOOM_DEFAULT;
	    }

	    if (this.myFormat == undefined) {
    	    this.myFormat = FORMAT_DEFAULT;
	    }

	    if (typeof(window['this.myStyles'])=="undefined") this.myStyles="";
	    var lULP = new GPoint(a.x*256,(a.y+1)*256);
	    var lLRP = new GPoint((a.x+1)*256,a.y*256);
	    var lUL = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lULP,b,c);
	    var lLR = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lLRP,b,c);

	    // switch between Mercator and DD if merczoomlevel is set
	    // NOTE -it is now safe to use Mercator exclusively for all zoom levels (if your WMS supports it)
	    // so you can just use the two lines of code below the IF (& delete the ELSE)
    	
	    if (this.myMercZoomLevel!=0 && map.getZoom() < this.myMercZoomLevel) {
		    var lBbox=dd2MercMetersLng(lUL.x)+","+dd2MercMetersLat(lUL.y)+","+dd2MercMetersLng(lLR.x)+","+dd2MercMetersLat(lLR.y);
		    //Change for GeoServer - 41001 is mercator and installed by default.
		    var lSRS="EPSG:54004";
	    } else {
		    var lBbox=lUL.x+","+lUL.y+","+lLR.x+","+lLR.y;
		    var lSRS="EPSG:4326";
	    } 
	    var lURL=this.myBaseURL;
	    lURL+="&REQUEST=GetMap";
	    lURL+="&SERVICE=WMS";
	    lURL+="&VERSION=1.1.1";
	    lURL+="&LAYERS="+this.myLayers;
	    lURL+="&STYLES="+this.myStyles;
	    lURL+="&FORMAT="+this.myFormat;
	    lURL+="&BGCOLOR=0xFFFFFF";
	    lURL+="&TRANSPARENT=TRUE";
	    lURL+="&SRS="+lSRS;
	    lURL+="&BBOX="+lBbox;
	    lURL+="&WIDTH=256";
	    lURL+="&HEIGHT=256";
	    lURL+="&reaspect=false";
	    //document.write(lURL + "<br/>")
	    //alert(" url is " + lURL);
	    return lURL;
    }

    function customOpacity() { return this.myOpacity; }


<!-- WMS SCRIPT ENDS HERE -->




	if (GBrowserIsCompatible())
	{





		var allowedBounds = new GLatLngBounds(new GLatLng(51,0), new GLatLng(53.0,2.0));
		
		map = new GMap2(document.getElementById(MapDivID));

		map.returnToSavedPosition()

//		if (getURLParameters("X")) {
//				var x = getURLParameters("X");
//				var y = getURLParameters("Y");
//				var mapScale = getURLParameters("mapScale");
//				if (x=='') {
//					
//					map.setCenter(new GLatLng(51.46449,-0.5724), 15);
//				} else {
//					map.setCenter(new GLatLng(parseFloat(y),parseFloat(x)), parseFloat(mapScale));
//				}
//		  		}
//	alert(MapDivID);


  // add custom copyright collection
  var copyrightstatement='<br/>Crown Copyright. All rights reserved.<br/>Norfolk County Council Licence No.100019340<br/>';

  var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 0, copyrightstatement);
  var copyrightCollection = new GCopyrightCollection('');
  copyrightCollection.addCopyright(copyright);




if (MapDivID == 'SmallSearchMap') {
// small search map
//	alert('im small');


	var myTileLayer = new GTileLayer(copyrightCollection,1,17);


//	var myTileLayer = new GTileLayer(new GCopyrightCollection(""),1,17);
//        myTileLayer.myBaseURL='http://www.esdm.no-ip.com/scripts/mapserv460.exe?map=C:/Inetpub/wwwroot/Mapserverservice/Map/WMSNHEdemo.map&'

//http://www.tilecache.no-ip.com/CallCrop.aspx? is ESDM proxy that gets larger image and returns the middle bit, to avoid tile edge effects
        myTileLayer.myBaseURL='http://www.tilecache.no-ip.com/CallCrop.aspx?' + WMSURL + '';
//        alert(WMSURL);
        myTileLayer.myLayers='NorfolkCounty';
        myTileLayer.myFormat='image/png';
	    myTileLayer.getTileUrl=CustomGetTileUrl;
	    myTileLayer.myOpacity=1;
        myTileLayer.getOpacity=customOpacity;
		
        var layer1=[G_NORMAL_MAP.getTileLayers()[0],myTileLayer];
		var custommap1 = new GMapType(layer1, G_NORMAL_MAP.getProjection(), "Blah");
		map.addMapType(custommap1);
		
		map.setCenter(new GLatLng(52.7,1.0), 7);
		map.addControl(new GSmallMapControl());

		var mt = map.getMapTypes();
		for (var i=0; i<mt.length; i++) {
		    mt[i].getMinimumResolution = function() {return 5;}
//		}


//				map.addControl(new GLargeMapControl());
//				map.addControl(new GMapTypeControl());
//				map.addControl(new GOverviewMapControl());
//				map.addControl(new GScaleControl());
                map.setMapType(custommap1);



		GEvent.addListener(map, "click", function(marker, point) {
		    map.clearOverlays();


		    if (marker) {
			map.removeOverlay(marker);
			document.forms[0].ctl00_ContentPlaceHolder1_txtOSRef.value = "";
		    }
		    else {
			map.addOverlay(new GMarker(point));
			var ll2 = new LatLng(point.y, point.x);
			var os2 = ll2.toOSRef();
			document.forms[0].ctl00_ContentPlaceHolder1_txtEasting.value = os2.easting.toFixed(0);
			document.forms[0].ctl00_ContentPlaceHolder1_txtNorthing.value = os2.northing.toFixed(0);
			document.forms[0].ctl00_ContentPlaceHolder1_txtOSRef.value = os2.toSixFigureString();
		    }
		});

		GEvent.addListener(map, "move", function() {
		    checkBounds();
		});

		function checkBounds()
		{
		    if (allowedBounds.contains(map.getCenter())) {
			return;
		    }

		    var C = map.getCenter();
		    var X = C.lng();
		    var Y = C.lat();

		    var AmaxX = allowedBounds.getNorthEast().lng();
		    var AmaxY = allowedBounds.getNorthEast().lat();
		    var AminX = allowedBounds.getSouthWest().lng();
		    var AminY = allowedBounds.getSouthWest().lat();

		    if (X < AminX) {X = AminX;}
		    if (X > AmaxX) {X = AmaxX;}
		    if (Y < AminY) {Y = AminY;}
		    if (Y > AmaxY) {Y = AmaxY;}

		    map.setCenter(new GLatLng(Y,X));
		} 

	}
	
	} else {
	// big search map
//alert('big');
	      map = new GMap2(document.getElementById(MapDivID));
	      map.addControl(new GLargeMapControl());
//	      map.addControl(new GMapTypeControl());
	      map.addControl(new GScaleControl());
// removed CF 22/10/09 as slows everything down          map.addControl(new GOverviewMapControl());
          
         
          
				var x = getURLParameters("X");
				var y = getURLParameters("Y");
				var mapScale = getURLParameters("mapScale");
				if (x=='') {
					map.setCenter(new GLatLng(52.7,1.0), 9);
				} else {
					map.setCenter(new GLatLng(parseFloat(y),parseFloat(x)), parseFloat(mapScale));
				}


				if ( get_cookie ( "minLat" ) )
					{
						var minLat = get_cookie ( "minLat" );
						var maxLat = get_cookie ( "maxLat" );
						var minLong = get_cookie ( "minLong" );
						var maxLong = get_cookie ( "maxLong" );
						var bounds = new GLatLngBounds;
						bounds.extend(new GLatLng(minLat, minLong));
						bounds.extend(new GLatLng(maxLat, maxLong));
						map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)); 
					}

				var center = map.getCenter();


<!-- INCLUDE WMS LAYER HERE (START)-->

	var myTileLayer = new GTileLayer(copyrightCollection,1,17);

//	var myTileLayer = new GTileLayer(new GCopyrightCollection(""),1,17);
//        myTileLayer.myBaseURL='http://www.norfolkheritageexplorer.no-ip.org/scripts/mapserv.exe?map=D:\websites\WMS\Map\WMSNHEdemo.map&'
//http://www.tilecache.no-ip.com/CallCrop.aspx? is ESDM proxy that gets larger image and returns the middle bit, to avoid tile edge effects
        myTileLayer.myBaseURL='http://www.tilecache.no-ip.com/CallCrop.aspx?' + WMSURL + '';
//        alert(myTileLayer.myBaseURL);
        // comman-sep list. fails to retrieve last layer in the list for some reason
        // layers are drawn in the order specified here
        myTileLayer.myLayers='NHEareas,NHElines,NHEpoints,NorfolkCounty';
        myTileLayer.myFormat='image/png';
	    myTileLayer.getTileUrl=CustomGetTileUrl;
	    myTileLayer.myOpacity=01;
	    //myTileLayer.myOpacity=0.69;
        myTileLayer.getOpacity=customOpacity;

        var layer1=[G_NORMAL_MAP.getTileLayers()[0],myTileLayer];
		var custommap1 = new GMapType(layer1, G_NORMAL_MAP.getProjection(), "NHE/GYAM data");
		map.addMapType(custommap1);

		var mt = map.getMapTypes();
		for (var i=0; i<mt.length; i++) {
		    mt[i].getMinimumResolution = function() {return 5;}
		}



<!-- Check if user clicked and then do something  -->
		GEvent.addListener(map,"click",
		   function (overlay, point)
		   {
		        if(overlay)
		        { return; }
		   	    var pt = new GLatLng(point.y,point.x);
		        addInfoTipMarker(pt);
		    }
		);

<!-- Adds InfoTip when clicked -->
	   function addInfoTipMarker(pt){
   		var p = new GPoint(pt);
		// code from Lance on the Google Maps Group

		var b = map.getBounds();
		var sw = b.getSouthWest();
		var ne = b.getNorthEast();
		var w = sw.lng();
		var e = ne.lng();
		var n = ne.lat();
		var s = sw.lat();
		var ts = s;
		var tw = w;
		if(n<s) { s=n; n = ts; }
		if(e<w){ w=e; e = tw; }
		if(s<-90)s=-90;
		if(n>90)n=90;
		if(e>180)e=180;
		if(w<-180)w=-180;

		var span_ew = Math.abs(e - w);
		var span_ns = Math.abs(n - s);

// Evaluate width and height of current map DIV

		CurrentMapDIV = document.getElementById(MapDivID);

		CurrentMapDIVHeight=parseInt(CurrentMapDIV.style.height);
		CurrentMapDIVWidth=parseInt(CurrentMapDIV.style.width);
//alert(CurrentMapDIVHeight);
//		var width  = 768*span_ew/span_ns;
//		var height = 768;
		var width  = CurrentMapDIVWidth * span_ew / span_ns;
		var height = CurrentMapDIVHeight;

		var x = (pt.x - w) * width/span_ew;
		var y = (n - pt.y) * height/span_ns;

		var label1 = 'Info';
		//var label2 = 'Details';
		var htm = "";
		//var html2 = "You clicked on <br>" + pt;

		var URL = GetURL(x, y, w, s, e, n, width, height);

		//htm += '<a href="javascript:zoomIn('+p+');">Zoom In</a>&nbsp;|&nbsp;<a href="javascript:zoomOut('+p+');">Zoom Out</a><br><br>';
		htm += "<iframe marginwidth=\"10\" name=\"WMSToolTip\" id=\"WMSToolTip\" frameborder=0 style=\"width:300px;height:75px;border: 0px;\" src=\"";
		htm += URL;
		htm += "\" ></iframe>";
//		alert(htm);


		map.openInfoWindowHtml(pt, htm);
    //		map.openInfoWindowTabsHtml(pt, [new GInfoWindowTab(label1,html1), new GInfoWindowTab(label2,html2)])


	}

	function GetURL(x, y, w, s, e, n, width, height){
//		r = "http://www.esdm.no-ip.com/scripts/mapserv460.exe?map=C:/Inetpub/wwwroot/Mapserverservice/Map/WMSHostingDemo.map";
        r = ''+WMSURL+'';
//        alert(r);
		r+="&SERVICE=WMS";
		r+="&SRS=EPSG:4326";
		r+="&VERSION=1.1.1";
		r+="&REQUEST=GetFeatureInfo";
		r+="&X=" + parseInt(x);
		r+="&Y=" + parseInt(y);
		r+="&QUERY_LAYERS=Parishes,NHEpoints,NHEareas,NHElines";
		r+="&LAYERS=NHEpoints,NHEareas,NHElines";
		r+="&INFO_FORMAT=text/html";
		r+="&BBOX="+w+","+s+","+e+","+n;
		r+="&WIDTH="+parseInt(width)+"&HEIGHT="+ parseInt(height);
		r+="&FEATURE_COUNT=10";
		return r;
	}
	
<!-- INCLUDE WMS LAYER HERE (END)-->

// END ELSE MapDivID

<!-- Set cookies defining current view extent -->

		GEvent.addListener(map, 'moveend',function(){
		//alert ('setting cookie');
		set_cookie ( "minLat",map.getBounds().getSouthWest().lat() );
		set_cookie ( "maxLat",map.getBounds().getNorthEast().lat());
		set_cookie ( "minLong",map.getBounds().getSouthWest().lng() );
		set_cookie ( "maxLong",map.getBounds().getNorthEast().lng() );
		});

<!-- Switch to WMS view here - THIS NEEDS TO BE AT THE END!!! -->

		  map.setMapType(custommap1);
//		  alert('map type set');
		   
}
}
}


