/*--------------------------------------------------------------
map.js
For CentreMapsLive Ver. 2
Code for controlling the map
Lovell Jonhs Ltd.
01/01/10
--------------------------------------------------------------*/

//------------------------------------------------------------GLOBALS	
var map;								//Openlayers map layer
var licensedLayer;						//Vector layer that stores the MasterMap licensed areas (invisible to the user)
var licensed10kLayer;					//Vector layer that stores the OS10K licensed areas (invisible to the user)
var extentLayer;						//Vector Layer for the map extents
var baseLayer;							//Layer that contains the mapping
var annoLayer;							//Layer that contains the user annotation 
var aerialLayer;						//Layer for Aerial imagery				
var markerLayer;						//Openlayers layer for adding markers (Used for marking searched points)
var previousLayer;						//Layer that stores previous order extents
var paperLayer;							//Layer to define paper size extent (ie. not the data extent)
var NALayer;							//Layer to define not available areas for a data product
var mmLayer;							//Layer for MasterMap data
var captureLayer;						//Layer for capturing MasterMap shapes
var extentLayer2;						//Vector Layer for the map extents associated map extents (used for the muti-extent products)
var URMLayer;							//Layer to store extents of Urban-Rural-Moorland areas
var SVLayer;							//Layer to store Google StreetView location point
var base10kLayer;
var drawPolyControl;					//Control that handles defining map extents (POLY)
var drawPointControl;					//Control that handles defining map extents (POINT)
var modifyControl;						//Control that handles modifying map extent features
var drawCapturePolyControl;				//Controls to define capture shapes
var drawCapturePointControl;
var drawAnnoPolyControl;				//Controls that handle defining user anno (POLY,LINE,RECT,CIRCLE)
var drawAnnoLineControl;
var drawAnnoRectControl;
var drawAnnoCircleControl;
var drawAnnoLabelControl;
var drawSVPointControl;					//Control to define the location of Google StreetView locator 
var modifyAnnoControl;					//Control that handles modifying user anno features
var modifySVControl;					//Control that handles modifying Google StreetView locator 
var selFeatureControl;					//Control that handles selecting point features (used to show popup info)
var redrawingExtent = false				//Defines if re-drawing the extent from account area
var theCurrentExtentID;					//Extent ID of the extent added
var storedPassedExtent;					//Extent passed to the map page
var storedHasUserShapes;				//User annotation passed to the map page
var storedShapesFrom;					//Shapes source passed to the map page (Shopping basket or account area)
var storedGSInfoString;					//Groundsure info passed to the map page
var storedSelectedScale;				//Print scale passed to the map page
var zchm;								//Product choice zchm
var toolbox;							//Toolbox area along the top of map
var extentColours = new Array("#ED0489","#000000","#FF0000","#00FF00","#0000FF"); //,"#999999");			//Colours of the differnt map extents
var mmLicencePrice = "1.20";				//Price for a OS MasterMap licensed view area
var mmLicencePriceExtend = "0.60";			//Price to extend an OS MasterMap licensed view area
var the10kLicSize = 4392 ;   				//Radius of OS10K licenced areas (in metres)
var getPreviewsReq;							//Ajax request objects
var getCreditReq;
var getURMReq;
var get10kPreviewsReq;
var canHideIt = false;  						//Setting that signifies we hide the toolbox on mouse over (initially false to stop the search box cleaing off)
var thisYear = new Date().getFullYear();
var shiftIsDown = false;
var timerId;
var timerId2;
var updatingExtent = -1;						//Extent id stored when updating paper sizes
var showBlom = false;							//Retrieve BlomURBEX coverage
var applyToSelected = true;						//Flag to allow the current extent that is drawn to be applied to the selected product
var boundsForLicenceCheckPreAutoZoom;			//Bounds of view extent which we need to check falls in licensed area when trying to zoom the data extent.		
var checkLicenceAfterGetURM = true;				//Define if we need to perform a licence check after retrieving the U-R-M coverage
var intermediateScaleCheckScale = 5000;			//Map scale below which large scale mapping available (OS MasterMap hybrid) - ie can continue showing on zoom out or request from the map layers tab
var largeScaleCheckScale = 2000;				//Map scale below which large scale mapping available (OS MasterMap hybrid)
var blomCheckScale = 500000;					//Map scale below which BLOMUrbex coverage is checked
var clickCountScale = 453543.552;				//Map scale which if below we record map clicks
var tenKCheckScale = 7015.141948699951;			//Map scale at which below will show 10k mapping (either OS10k or StreetView)		
var aerialCheckScale = 1750;					//Map scale at which below aerial imager cannot be shown
var mapLayerOptions = new Array("mapLayersRoad","mapLayersAerial","mapLayersOther");			//Mapping type content
//Set up the arrays that store what data is shown at each zoom scale
var baseMappingData = new Array("OS Miniscale","OS Miniscale","OS 250K","OS 250K","OS 50K","OS 25K","OS 25K","OS StreetView","OS MasterMap");
var mapScales = new Array(453543.552,226771.776,113385.888,56692.944,28346.472,14173.236,7086.618,2834.6472,1417.3236);

//Max extent of the GB and NI mapping 
var fullExtentGB = new Array(10000,-7500,707500,1290000);
var fullExtentNI = new Array(157488,281847,394653,491645);

//Fixed point display
var popup;
var feature = null;
var currentViewWidth = 1100000;   							//Current view size (used to check if fixed points can be show)
var currentViewHeight = 1100000;
var fixedCheckBoxes = new Array("chkSurvey"); //,"chkBench");	//Fixed products available
var fixedThresholdSize = 2000;     							//View width in which fixed points can be shown
var fixedLayerArray = new Array();							//Fixed layers added to view
var fixedBufferDistance = 500;     							//Buffer distance around map extent in which to retrieve points
var fixedCentreX = null;									//Centre of map in which current set of points were retrieved in reference to
var fixedCentreY = null;
var fixedLayer;												//Purchasible fixed layer	
var fixedBuyCentreX = null;									//Centre of map in which current set of points were retrieved in reference to
var fixedBuyCentreY = null;
var svPanorama;												//Google StreetView Panorama object
var svService;											//Google StreetView Service object
var theSVSate = "off"

//Define global styling info
OpenLayers.Feature.Vector.style['default']['strokeWidth'] = '3';
OpenLayers.Feature.Vector.style['default']['fillColor'] = '#FFFFFF';
OpenLayers.Feature.Vector.style['default']['strokeColor'] = '#000000';
OpenLayers.Feature.Vector.style['default']['fillOpacity'] = '0.3';
OpenLayers.Feature.Vector.style['default']['graphicOpacity'] = '1';
OpenLayers.Feature.Vector.style['default']['strokeDashstyle'] = 'none';
OpenLayers.Feature.Vector.style['select']['strokeWidth'] = '3';
OpenLayers.Feature.Vector.style['select']['fillColor'] = '#00FFFF';
OpenLayers.Feature.Vector.style['select']['strokeDashstyle'] = 'none';
OpenLayers.Feature.Vector.style['select']['strokeColor'] = '#00FFFF';
OpenLayers.Feature.Vector.style['select']['fillOpacity'] = '0.5';
OpenLayers.Feature.Vector.style['select']['graphicOpacity'] = '1';
var annoStyle = new OpenLayers.StyleMap(OpenLayers.Util.applyDefaults(
        {fillColor: "#000000", fillOpacity: 0.3, strokeWidth: 1, graphicOpacity: 1, strokeDashstyle: "none", strokeColor: "#000000"},
        OpenLayers.Feature.Vector.style["default"]));
var paperStyle = new OpenLayers.StyleMap(OpenLayers.Util.applyDefaults(
        {fillColor: "#666666", fillOpacity: 0.7, strokeWidth: 2, graphicOpacity: 1, strokeDashstyle: "dash", strokeColor: "#000000"},
        OpenLayers.Feature.Vector.style["default"]));
var NAStyle = new OpenLayers.StyleMap(OpenLayers.Util.applyDefaults(
        {fillColor: "#666666", fillOpacity: 0.6, strokeWidth: 0, graphicOpacity: 1, strokeDashstyle: "none", strokeColor: "none"},
        OpenLayers.Feature.Vector.style["default"]));
var licensedStyle = new OpenLayers.StyleMap(OpenLayers.Util.applyDefaults(
        {fillColor: "none", fillOpacity: 0.1, strokeWidth: 2, graphicOpacity: 1, strokeDashstyle: "dash", strokeColor: "#FF0000"},
        OpenLayers.Feature.Vector.style["default"]));
var licensedStyle2 = new OpenLayers.StyleMap(OpenLayers.Util.applyDefaults(
        {fillColor: "none", fillOpacity: 0, strokeWidth: 0, graphicOpacity: 1, strokeDashstyle: "dash", strokeColor: "none"},
        OpenLayers.Feature.Vector.style["default"]));
var urmStyle = new OpenLayers.StyleMap(OpenLayers.Util.applyDefaults(
        {fillColor: "none", fillOpacity: 0, strokeWidth: 0, graphicOpacity: 1, strokeDashstyle: "none", strokeColor: "none"},
        OpenLayers.Feature.Vector.style["default"]));
var pinStyleMap = new OpenLayers.StyleMap({pointRadius: 20, externalGraphic: 'http://shop.centremapslive.co.uk/images/crosshair.gif'});
var svStyleMap = new OpenLayers.StyleMap({pointRadius: 20, rotation:0, externalGraphic: 'http://shop.centremapslive.co.uk/whitelabel/images/sv_icon.png'});

//-------------------------------------------------------------------------MAP SCRIPTS

//****************Initializes the map
function initMap(passedX,passedY,passedExtent,initMapExtent,theRegion,hasUserShapes,shapesFrom,selectedData,selectedDesc,selectedScale,selectedMaxSize,theGSInfoString,passedLicNo,passedSite,passedBlom,passedNILicNo){
	//IE6 redirection	
	if(is_ie6){
		window.location="mapie6.php";		
	}	
	//Store these variable as globals for use in recreating the extent
	storedPassedExtent = passedExtent;
	storedHasUserShapes = hasUserShapes;
	storedShapesFrom = shapesFrom;	
	storedGSInfoString = theGSInfoString;
	storedSelectedScale = selectedScale;
	//Store the blomURBEX show state
	showBlom = passedBlom;
	//Get list of all product categories to show on the page	
	getProductCategories(theRegion);
	//Define the map
	if(theRegion == "gb"){
		var mapOptions = {
			controls: [],
			maxExtent: new OpenLayers.Bounds(fullExtentGB[0],fullExtentGB[1],fullExtentGB[2],fullExtentGB[3]), 
			units: 'm',
			projection: new OpenLayers.Projection("EPSG:27700"),
			displayProjection: new OpenLayers.Projection("EPSG:27700"),					
			resolutions: [2500,1250,625,315,160,80,40,20,10,5,2.5,1,0.5,0.25,0.125,0.06,0.03]
		};
	}else{
		var mapOptions = {
			controls: [],
			maxExtent: new OpenLayers.Bounds(fullExtentNI[0],fullExtentNI[1],fullExtentNI[2],fullExtentNI[3]),
			units: 'm',
			projection: new OpenLayers.Projection("EPSG:29900"),
			displayProjection: new OpenLayers.Projection("EPSG:29900"),
			resolutions: [315,160,80,40,20,10,5,2.5,1,0.5,0.25,0.125,0.06,0.03]    //2500,1250,625, (smaller resolutions not needed)
		};
	}
	map = new OpenLayers.Map('map',mapOptions);
	map.fractionalZoom = false;								//Only allow pre-defined zoom levels				

	//Define the base layer (OS or UKMap data)
	if(theRegion == "gb"){
		//NON TILECACHE VERSIONbaseLayer = new OpenLayers.Layer.WMS("gb", "http://shop.centremapslive.co.uk/ogcwebserver/wms.exe?",
		//{layers: 'testsmallscale', isBaseLayer: true, format: "image/png; "});		
		baseLayer = new OpenLayers.Layer.WMS("gb", "http://shop.centremapslive.co.uk/tilecache/tilecache.py?", 
		{layers: 'testsmallscale', isBaseLayer: true, alwaysInRange: true,format: "image/png;"},{attribution: 'Mapping &copy; Ordnance Survey Crown Copyright ' + thisYear + '. Licence Number ' + passedLicNo + '.' , 'buffer':0});
		base10kLayer = new OpenLayers.Layer.WMS("os10k", "http://shop.centremapslive.co.uk/tilecache/tilecache.py?", 
		{layers: 'gb10kmapping', isBaseLayer: true, alwaysInRange: true,format: "image/png;"},{attribution: 'Mapping &copy; Ordnance Survey Crown Copyright ' + thisYear + '. Licence Number ' + passedLicNo + '.' , 'buffer':0});		
	}else{		
		//NON TILECACHE VERSIONbaseLayer = new OpenLayers.Layer.WMS("ni", "http://shop.centremapslive.co.uk/ogcwebserver/wms.exe?",
		//{layers: 'NorthernIrelandMapWMS', isBaseLayer: true, format: "image/png; "},{attribution: 'Mapping &copy; Ordnance Survey Northern Ireland Crown Copyright 2009.'});		
		baseLayer = new OpenLayers.Layer.WMS("ni", "http://shop.centremapslive.co.uk/tilecache/tilecache.py?", 
		{layers: 'nimapping', isBaseLayer: true, alwaysInRange: true, format: "image/png;"},{attribution: 'Mapping &copy; LPS (Ordnance Survey) Northern Ireland Crown Copyright ' + thisYear + '. Licence Number ' + passedNILicNo + '.' , 'buffer':0});		
	}

	//Define the aerial photo layer
	if(theRegion == "gb"){	
		//NON TILECACHE VERSIONaerialLayer = new OpenLayers.Layer.WMS("aerial", "http://www.getmapping.com/IeDirectImage/getmappingwms.aspx?login=andy300&password=centremap&&country=compuk&",
		//{layers: 'composite_image', isBaseLayer: true, format: "image/jpeg; "});	
		aerialLayer = new OpenLayers.Layer.WMS("aerial", "http://shop.centremapslive.co.uk/tilecache/tilecache.py?",
		{layers: 'composite_image', isBaseLayer: true,alwaysInRange: true,format: "image/png;"},{attribution: 'Imagery &copy; Getmapping PLC Copyright 2010.' , 'buffer':0});
	}else{
		//NON TILECACHE VERSIONaerialLayer = new OpenLayers.Layer.WMS("aerial", "http://shop.centremapslive.co.uk/ogcwebserver/wms.exe?",
		//{layers: 'NorthernIrelandAerialWMS', isBaseLayer: true, format: "image/png; "},{attribution: 'Imagery &copy; LPS (Ordnance Survey) Northern Ireland Crown Copyright 2010. Licence Number 100,348.'});	
		aerialLayer = new OpenLayers.Layer.WMS("aerial", "http://shop.centremapslive.co.uk/tilecache/tilecache.py?",
		{layers: 'niaerial', isBaseLayer: true,alwaysInRange: true,format: "image/jpeg;"},{attribution: 'Imagery &copy; LPS (Ordnance Survey) Northern Ireland Crown Copyright ' + thisYear + '. Licence Number ' + passedNILicNo + '.' , 'buffer':0});
	}
	
	//MasterMap layer
	//OLD VER 1mmLayer = new OpenLayers.Layer.WMS("mm", "http://shop.centremapslive.co.uk/ogcwebserver/wms.exe?",
	//{layers: 'testsmallscale'}, {isBaseLayer: false,opacity: 0.3, format: "image/png; "});
	mmLayer = new OpenLayers.Layer.WMS("mm", "http://shop.centremapslive.co.uk/tilecache/tilecache.py?",
	{layers: 'testosmmv3'}, {isBaseLayer: false, alwaysInRange: true, format: "image/png; PhotometricInterpretation=RGBA",attribution: 'Mapping &copy; Ordnance Survey Crown Copyright ' + thisYear + '. Licence Number ' + passedLicNo + '.' , 'buffer':0});	
		
	//Set up all overlay layers - for map extent, user annotation, previous order, data not available, MasterMap licensed layers
	extentLayer = new OpenLayers.Layer.Vector("Map Extent");
	annoLayer = new OpenLayers.Layer.Vector("Annotation");
	previousLayer = new OpenLayers.Layer.Vector("Previous");
	paperLayer = new OpenLayers.Layer.Vector("Paper",{styleMap: paperStyle});
	extentLayer2 = new OpenLayers.Layer.Vector("Map Extent 2");
	NALayer = new OpenLayers.Layer.Vector("Not Available",{styleMap: NAStyle});
	captureLayer = new OpenLayers.Layer.Vector("Shape Capture",{styleMap: annoStyle});
	markerLayer = new OpenLayers.Layer.Vector("Markers",{styleMap: pinStyleMap});	
	licensedLayer = new OpenLayers.Layer.Vector("Licensed",{styleMap: licensedStyle});
	licensed10kLayer = new OpenLayers.Layer.Vector("Licensed10k",{styleMap: licensedStyle2});
	URMLayer = new OpenLayers.Layer.Vector("U-R-M",{styleMap: urmStyle});	
	SVLayer = new OpenLayers.Layer.Vector("SV Locator",{styleMap: svStyleMap});

	//Watermark layer
	watermark = new OpenLayers.Layer.Watermark('watermark','http://shop.centremapslive.co.uk/images/' + passedSite + '/mapwatermark.gif',
	{isBaseLayer:false,opacity:0.25,tileSize: new OpenLayers.Size(780,325)});

	//Add layers to map
	if(theRegion == "gb"){
		map.addLayers([baseLayer,base10kLayer,aerialLayer,URMLayer,mmLayer,watermark,NALayer,licensedLayer,licensed10kLayer,previousLayer,extentLayer,paperLayer,extentLayer2,annoLayer,captureLayer,markerLayer,SVLayer]);
	}else{
		map.addLayers([baseLayer,aerialLayer,watermark,NALayer,previousLayer,extentLayer,paperLayer,extentLayer2,annoLayer,captureLayer,markerLayer,SVLayer]);
	}
	
	//Ensure MasterMap layer initially hidden
	mmLayer.setVisibility(false);	
		
	//Set the initial extent of the map and zoom to it	
	if(initMapExtent != ""){			//Initialize to the passed map extent if one is set
		var extentOk = true;
		var extentArray = initMapExtent.split(",");
		//Check extent OK 
		if(extentArray.length != 4){
			extentOk = false;
		}else{
			if((extentArray[0] > extentArray[2]) || (extentArray[1] > extentArray[3])){
				extentOk = false;
			}
		}
		if(extentOk){	
			var initialExtentBounds = new OpenLayers.Bounds(extentArray[0],extentArray[1],extentArray[2],extentArray[3]);		
		}else{
			if(theRegion == "gb"){
				var initialExtentBounds = new OpenLayers.Bounds(fullExtentGB[0],fullExtentGB[1],fullExtentGB[2],fullExtentGB[3]);
			}else{
				var initialExtentBounds = new OpenLayers.Bounds(fullExtentNI[0],fullExtentNI[1],fullExtentNI[2],fullExtentNI[3]);
			}
		}
		initMapExtent = "";	
	}else{
		if(theRegion == "gb"){
			var initialExtentBounds = new OpenLayers.Bounds(fullExtentGB[0],fullExtentGB[1],fullExtentGB[2],fullExtentGB[3]);
		}else{
			var initialExtentBounds = new OpenLayers.Bounds(fullExtentNI[0],fullExtentNI[1],fullExtentNI[2],fullExtentNI[3]);
		}
	}
	if (!map.getCenter()) map.zoomToExtent(initialExtentBounds);
		
	//Adjust the map extent (move up) so we don't have too much white space at the top (resolution of the first zoom level should be higher)	
	var curentMapHeight = map.getExtent().getHeight();
	var heightAdjustment = curentMapHeight - 1290000;
	var newInitialExtentBounds = new OpenLayers.Bounds(10000,(0-heightAdjustment),707500,1290000);
	map.zoomToExtent(newInitialExtentBounds);
		
		
	//Add map controls
	//map.addControl(new OpenLayers.Control.LayerSwitcher());			//For testing
	//map.addControl(new OpenLayers.Control.Scale());				//For testing
	map.addControl(new OpenLayers.Control.Attribution({'div':OpenLayers.Util.getElement('copyrightdiv')}));
	//Set properties of pan-zoom
	var thePanZoomBarControl = new OpenLayers.Control.PanZoomBar({'div':OpenLayers.Util.getElement('panZoomLayer')});
	thePanZoomBarControl.slideFactor = 150;
	map.addControl(thePanZoomBarControl);
  	map.addControl(new OpenLayers.Control.Navigation());
	map.addControl(new OpenLayers.Control.ScaleLine({'div':OpenLayers.Util.getElement('scalediv2')})); 
    map.addControl(new OpenLayers.Control.MousePosition({'div':OpenLayers.Util.getElement('outputCoords2'),'suffix':'N','separator': 'E ','numDigits':0}));

	//Draw controls - used for defining map extents
	drawPolyControl = new OpenLayers.Control.DrawFeature(extentLayer,OpenLayers.Handler.Polygon);
	map.addControl(drawPolyControl);	
	drawPointControl = new OpenLayers.Control.DrawFeature(extentLayer,OpenLayers.Handler.Point);
	map.addControl(drawPointControl);
	
	//Draw controls - used for defining user annotation
	drawAnnoRectControl = new OpenLayers.Control.DrawFeature(annoLayer, OpenLayers.Handler.RegularPolygon, {handlerOptions: {sides: 4,irregular: true}});
	map.addControl(drawAnnoRectControl);
	drawAnnoCircleControl =  new OpenLayers.Control.DrawFeature(annoLayer, OpenLayers.Handler.RegularPolygon, {handlerOptions: {sides: 75}});
	map.addControl(drawAnnoCircleControl)
	drawAnnoPolyControl = new OpenLayers.Control.DrawFeature(annoLayer,OpenLayers.Handler.Polygon);
	map.addControl(drawAnnoPolyControl);
	drawAnnoLineControl = new OpenLayers.Control.DrawFeature(annoLayer,OpenLayers.Handler.Path);
	map.addControl(drawAnnoLineControl);
	drawAnnoLabelControl = new OpenLayers.Control.DrawFeature(annoLayer,OpenLayers.Handler.Point);
	map.addControl(drawAnnoLabelControl);
	
	//Draw controls - used for capturing MasterMap shapes	
	drawCapturePolyControl = new OpenLayers.Control.DrawFeature(captureLayer,OpenLayers.Handler.Polygon);
	map.addControl(drawCapturePolyControl);
	drawCapturePointControl = new OpenLayers.Control.DrawFeature(captureLayer,OpenLayers.Handler.Point);
	map.addControl(drawCapturePointControl);
	
	//Control to add the Google Streetview locator marker
	drawSVPointControl = new OpenLayers.Control.DrawFeature(SVLayer,OpenLayers.Handler.Point);
	map.addControl(drawSVPointControl);
	
	//Modify controls for extent
	modifyControl = new OpenLayers.Control.ModifyFeature(extentLayer);	
	map.addControl(modifyControl);

	//Modify controls for user anno
	modifyAnnoControl = new OpenLayers.Control.ModifyFeature(annoLayer);	
	map.addControl(modifyAnnoControl);
	
	//Modify controls for Google StreetView locator
	modifySVControl = new OpenLayers.Control.ModifyFeature(SVLayer);	
	map.addControl(modifySVControl);

	//Define map events 
	//Re-Centre the map if the extent is added or moved
 	extentLayer.events.register('featureadded', extentLayer, function(evt) { 
		if(extentLayer.features.length > 0){
			sndDrawCntReq();							//Update draw counter for royalty returns (if GB and below scale tolerance)
			//Define extent ID	
			if(updatingExtent != -1){					//Stored extentID (updating the extent - paper sizes only - used this extent no) 
				var extentNo = updatingExtent;
				updatingExtent = -1;
			}else{
				//Apply an ID to the extent	
				if(extentLayer.features.length == 1){
					var extentNo = 1;
				}else{
					//Get the next id
					var prevNo = 0;
					for(p=0; p < extentLayer.features.length;p++){
						var testID = extentLayer.features[p].attributes.id;
						if(testID != null){
							var testFeatureID = Number(testID.substring((testID.length-1),testID.length));
							if(p==0){
								var prevNo = testFeatureID;
							}else if(testFeatureID > prevNo){
								prevNo = testFeatureID;						
							}
						}
					}
					var extentNo = Number(prevNo) + 1;
				}
			}
			var extentId = "Extent " + String(extentNo);
			theCurrentExtentID = extentId;	
			var theCurrentExtentFeature = extentLayer.features[extentLayer.features.length-1];
			theCurrentExtentFeature.attributes.id = extentId; 
			//Store an attribute that defines that this extent is a fixed size
			if(document.varform.extentinput.value == "gsmap"){
				theCurrentExtentFeature.attributes.isfixed = "yes";
			}
			//Apply a default style 
			defExtentStyle = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
			//Get extent colour and label
			var theExtentColour = extentColours[extentNo-1];
			defExtentStyle.label= String(extentNo)			
			defExtentStyle.fillColor = theExtentColour;
			defExtentStyle.strokeColor = theExtentColour;			
			defExtentStyle.fillOpacity = 0.15;				
			defExtentStyle.fontSize= "20px";
			defExtentStyle.fontFamily= "Arial";
			defExtentStyle.fontWeight= "bold";
			if(String(extentLayer.features[extentLayer.features.length-1].geometry).indexOf("POINT") == -1){	
				defExtentStyle.labelAlign= "ct";
			}else{
				defExtentStyle.labelAlign= "lb";
			}
			if(is_ie){
				defExtentStyle.cursor = "hand";	
			}else{
				defExtentStyle.cursor = "pointer";
			}			
			defExtentStyle.pointRadius = 10;					
			defExtentStyle.labelXOffset = 20;   
			defExtentStyle.labelYOffset = 20;
			//if(is_ie7down == false){
			//	defExtentStyle.fontColor = "#ffffff";  
			//	defExtentStyle.labelPadding = "5px";
			//	defExtentStyle.labelBackgroundColor = theExtentColour;
			//	defExtentStyle.labelBorderColor= theExtentColour;
			//	defExtentStyle.labelBorderSize= "1px"; 
			//}else{
			defExtentStyle.fontColor = theExtentColour;  
			//}
			theCurrentExtentFeature.style = defExtentStyle;		  
			extentLayer.redraw();
			//Zoom to shape
			if((document.varform.data.value.toLowerCase() == "gs1_1") || (document.varform.extentinput.value == "paper") || (document.varform.ismultiextent.value == "yes")){ 
				//No need to zoom to the extent for paper or multi-extent product (outer extent will be zoomed to when it is added)	
			}else{		
				zoomToDataExtent(theCurrentExtentFeature);	
			}
			//Add paper size attribute to paper extent (need to apply this to the associated extent outlines).
			if(document.varform.extentinput.value == "paper"){
				theCurrentExtentFeature.attributes.papersize = document.varform.papersize.value;
			}
			//Add extent to the dropdown list (so it can be applied to a product)
			addExtentToList(extentNo);			
			//Apply extent id to the selected product and retrieve the price
			if(applyToSelected){													//This will be false when the extent is re-drawn as a result of updating the sheet size 
				var selectedProductIndex = getSelectedProductIndex();
				if(selectedProductIndex != -1) {									
					if(redrawingExtent){				//If re-drawing the extent from account area, don't promt user to apply this extent
						redrawingExtent = false;												//Reset
						applyExtentToSelected(selectedProductIndex,extentId,extentNo)
					}else{
						var testIndex = getNextEmptyIndex();
						if(testIndex == 1){										//There is no selected product - prompt to apply choose product			
							showDialog('',"Please choose a product to apply to this data extent from the list on the left.<br/><br/><input type='button' value='Close' id='closeButton' onclick='hideDialog();' >",'prompt');
						}else if(testIndex == 2){								//There is only one selected product - so don't prompt to apply - just do it			
							applyExtentToSelected(selectedProductIndex,extentId,extentNo);
						}else{
							var dialogContent = "Apply this data extent to the selected product?<br/><br/><input type='button' value='Yes' id='yesButton' onclick='applyExtentToSelected(\"" + selectedProductIndex + "\",\"" + extentId+  "\",\"" + extentNo + "\");'>  <input type='button' value='No' id='noButton' onclick='hideDialog();' >"
							showDialog('',dialogContent,'prompt');	
						}
					}
				}else{
					showDialog('',"Please choose a product to apply to this data extent from the list on the left.<br/><br/><input type='button' value='Close' id='closeButton' onclick='hideDialog();' >",'prompt');
				}
			}else{					//Ensure pricing is cleared
				var selectedProductIndices = getAssociatedExtents(extentId);
				for(c=0;c<selectedProductIndices.length;c++){
					updatePrice(selectedProductIndices[c]);
				}
			}
			//Show the extent info area 
			var selObj = document.getElementById(extentId+"container");
			if(selObj != null){
				getExtentInfo();
			}
			//After drawing shape allow modification of the shape on click
			if(selFeatureControl != null){ 
				selFeatureControl.deactivate();
			}
			if((document.varform.extentinput.value == "paper") || (document.varform.extentinput.value == "gsmap")){
				modifyControl.mode = OpenLayers.Control.ModifyFeature.DRAG;
				modifyControl.activate();
			}else if((document.varform.extentinput.value == "radius") || (document.varform.extentinput.value == "ground") || (document.varform.extentinput.value == "extent") || document.varform.extentinput.value == "user"){
				modifyControl.mode = OpenLayers.Control.ModifyFeature.DRAG;
				modifyControl.mode |= OpenLayers.Control.ModifyFeature.RESIZE;
				modifyControl.mode |= OpenLayers.Control.ModifyFeature.RESHAPE;
				modifyControl.activate();
			}else if(document.varform.extentinput.value == "osfixed"){	
				modifyControl.mode = OpenLayers.Control.ModifyFeature.DRAG;
				modifyControl.activate();
			}else{
				modifyControl.mode = OpenLayers.Control.ModifyFeature.DRAG;
				modifyControl.mode |= OpenLayers.Control.ModifyFeature.RESHAPE;
				modifyControl.activate();
			}										
		} 
		//Deactive the drawing	
		drawPolyControl.deactivate();
		drawPointControl.deactivate();
	}); 
	
	extentLayer.events.register('featuremodified', extentLayer, function(evt) { 
		if(extentLayer.features.length > 0){
			var theSelectedExtent = getTheSelectedExtent();
			theCurrentExtentID = theSelectedExtent.attributes.id;
			var geomString = String(theSelectedExtent.geometry);	 
		    geomString = geomString.substring(9,(geomString.length -2))
		 	zoomToDataExtent(theSelectedExtent);									//Zoom to the extent of selected extent							  
			//Redraw the paper extent if necessary
			if(paperLayer.features.length > 0){
				var mapScale = theSelectedExtent.attributes.datascale;
				var paperExtentRemoved = false;
				for(p=0;p < paperLayer.features.length;p++){
					if(paperLayer.features[p].attributes.id == theCurrentExtentID){		//Remove existing
						document.varform.papersize.value = paperLayer.features[p].attributes.papersize;		//Ensure the papersize is stored for retrieval
						paperLayer.removeFeatures(paperLayer.features[p]);
						paperExtentRemoved = true;
						break;
					}			
				}
				if(paperExtentRemoved){
					drawPaperDataExtent(0,0,mapScale,geomString,false);						//Redraw		
				}
			}
			//Redraw the multi extent if necessary
			if(extentLayer2.features.length > 0){
				var multiExtentRemoved = false;
				for(p=0;p <extentLayer2.features.length;p++){
					if(extentLayer2.features[p].attributes.id == theCurrentExtentID){		//Remove existing
						extentLayer2.removeFeatures(extentLayer2.features[p]);
						multiExtentRemoved = true;
						break;
					}			
				}
				if(multiExtentRemoved){
					defineFixedMapExtents(theSelectedExtent,"redraw");
				}
			}
			//Update the extent info area
			var selObj = document.getElementById(theCurrentExtentID+"info");
			if(selObj != null){	
				updateExtentInfo(theCurrentExtentID);
			}
			//Check what products are attached to this extent and update the price(s) accordingly
			var selectedProductIndices = getAssociatedExtents(theCurrentExtentID);
			var itemlist = "";
			for(c=0;c<selectedProductIndices.length;c++){
				updatePrice(selectedProductIndices[c]);
				//Check if any multi-supplier produx are attached to this extent
				if((document.getElementById("productLayers" + selectedProductIndices[c]).value != "") || ((document.getElementById("layersPrice" + selectedProductIndices[c]).value != 0) && (document.getElementById("layersPrice" + selectedProductIndices[c]).value != ""))){
					itemlist += " " + String(selectedProductIndices[c]);
					document.getElementById("productLayers" + selectedProductIndices[c]).value = "";			//Reset fields
					document.getElementById("layersPrice" + selectedProductIndices[c]).value = "0";
					document.getElementById("layeroverlays" + selectedProductIndices[c]).value = "";
					document.getElementById("layersPrices" + selectedProductIndices[c]).value = "";	
					if((document.varform.data.value == "NULL_AERIAL") || (document.varform.data.value == "NULL_HEIGHT")){
						var outputBreakdown = "<a href='javascript:showFurtherInfo(\"suppliers\"," + selectedProductIndices[c] + ");'>Click to show data suppliers</a>";	
					}else{
						var outputBreakdown = "<a href='javascript:showFurtherInfo(\"mastermap\"," + selectedProductIndices[c] + ");'>Add Aerial/Height?</a>";	
					}
					document.getElementById("furtherInfo" + selectedProductIndices[c]).innerHTML = outputBreakdown;
					//if this product is actually selected call getSupplierInfo()
					if(document.frmSelected.selectedproducts[selectedProductIndices[c]-1].checked){		
						if(document.varform.data.value.substring(0,4) == "OSMM"){
							document.getElementById("productsAvailable").innerHTML = "<div id='supplierinfoAerial_layer'></div><div id='supplierinfoHeight_layer'></div>";
							//zchm.slideIn();
							//To add later
							//getOverlaySupplierInfo("aerial",true);
							//timerId = setTimeout("getOverlaySupplierInfo('height',true)",5000);
							//getOverlaySupplierInfo("height",true);
						}else{
							//getSupplierInfo(true);
						}	
					}					
				}
			}
			if(itemlist != ""){
				showDialog('Warning','New suppliers will need to be defined for the selected item(s) "' + trim(itemlist) + '".<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			}						
		}
	}); 	
	//Actions after adding paper extent (add the appropriate id and reference to the paper size)
	paperLayer.events.register('featureadded', paperLayer, function(evt) { 
		if(paperLayer.features.length > 0){
			//Check what products are attached to this extent and update the price(s) accordingly
			var selectedProductIndices = getAssociatedExtents(theCurrentExtentID);
			var itemlist = "";
			for(c=0;c<selectedProductIndices.length;c++){
				updatePrice(selectedProductIndices[c]);
				//Check if any multi-supplier produx are attached to this extent
				if((document.getElementById("productLayers" + selectedProductIndices[c]).value != "") || ((document.getElementById("layersPrice" + selectedProductIndices[c]).value != 0) && (document.getElementById("layersPrice" + selectedProductIndices[c]).value != ""))){
					itemlist += " " + String(selectedProductIndices[c]);
					document.getElementById("productLayers" + selectedProductIndices[c]).value = "";			//Reset fields
					document.getElementById("layersPrice" + selectedProductIndices[c]).value = "0";
					document.getElementById("layeroverlays" + selectedProductIndices[c]).value = "";
					document.getElementById("layersPrices" + selectedProductIndices[c]).value = "";	
					if((document.varform.data.value == "NULL_AERIAL") || (document.varform.data.value == "NULL_HEIGHT")){
						var outputBreakdown = "<a href='javascript:showFurtherInfo(\"suppliers\"," + selectedProductIndices[c] + ");'>Click to show data suppliers</a>";	
					}else{
						var outputBreakdown = "<a href='javascript:showFurtherInfo(\"mastermap\"," + selectedProductIndices[c] + ");'>Add Aerial/Height?</a>";	
					}
					document.getElementById("furtherInfo" + selectedProductIndices[c]).innerHTML = outputBreakdown;
					//if this product is actually selected call getSupplierInfo()
					if(document.frmSelected.selectedproducts[selectedProductIndices[c]-1].checked){		
						if(document.varform.data.value.substring(0,4) == "OSMM"){
							document.getElementById("productsAvailable").innerHTML = "<div id='supplierinfoAerial_layer'></div><div id='supplierinfoHeight_layer'></div>";
							//zchm.slideIn();
							//To add later
							//getOverlaySupplierInfo("aerial",true);
							//timerId = setTimeout("getOverlaySupplierInfo('height',true)",5000);
							//getOverlaySupplierInfo("height",true);
						}else{
							//getSupplierInfo(true);
						}	
					}					
				}
			}
			if(itemlist != ""){
				showDialog('Warning','New suppliers will need to be defined for the selected item(s) "' + trim(itemlist) + '".<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			}
			var theCurrentPaperFeature = paperLayer.features[paperLayer.features.length-1];
			theCurrentPaperFeature.attributes.id = theCurrentExtentID;
			theCurrentPaperFeature.attributes.papersize = document.varform.papersize.value;
			var actualDataExtent = getFeatureExtentByID(theCurrentExtentID);
			zoomToDataExtent(actualDataExtent);
		}
	}); 
	//Actions after adding second extent of muti extent (add the appropriate id and style)
	extentLayer2.events.register('featureadded', extentLayer2, function(evt) { 
		if(extentLayer2.features.length > 0){
			var theCurrentExtentFeature = extentLayer2.features[extentLayer2.features.length-1];
			theCurrentExtentFeature.attributes.id = theCurrentExtentID;
			//Apply a default style 
			var extentNo = theCurrentExtentID.substring(6,theCurrentExtentID.length);
			defExtentStyle = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
			var theExtentColour = extentColours[extentNo-1];		
			defExtentStyle.fillColor = theExtentColour;
			defExtentStyle.strokeColor = theExtentColour;			
			defExtentStyle.fillOpacity = 0.15;
			if(is_ie){
				defExtentStyle.cursor = "hand";	
			}else{
				defExtentStyle.cursor = "pointer";
			}
			theCurrentExtentFeature.style = defExtentStyle;		  
			extentLayer2.redraw();
			//Show the extent info area 
			var selObj = document.getElementById(theCurrentExtentID+"container");
			if(selObj != null){	
				getExtentInfo();
			}
			zoomToDataExtent(theCurrentExtentFeature);
		}
	});
	//Actions after adding new annotation
 	annoLayer.events.register('featureadded', annoLayer, function(evt) {
		//Show the anno element styling options pane	
	 	if(document.varform.selectedTool.value == "drawline"){
			sndDrawCntReq();									//Update draw counter for royalty returns (if GB and below scale tolerance)	
			annoDrawingEnable('selusershape');
			storeUserAnno("line","");							//Define the unique id for the shape and  number of shapes	
		}else if(document.varform.selectedTool.value == "drawarrow"){	
			sndDrawCntReq();									//Update draw counter for royalty returns (if GB and below scale tolerance)
			annoDrawingEnable('selusershape');
			storeUserAnno("arrow","");							//Define the unique id for the shape and  number of shapes				
		}else if(document.varform.selectedTool.value == "drawpoly"){ 
			sndDrawCntReq();									//Update draw counter for royalty returns (if GB and below scale tolerance)
			annoDrawingEnable('selusershape');
			storeUserAnno("poly","");							//Define the unique id for the shape and  number of shapes	
		}else if(document.varform.selectedTool.value == "drawrect"){
			//Get the current feature
			var nofeatures = annoLayer.features.length
			var thecurrentFeature = annoLayer.features[nofeatures-1];
			if(String(thecurrentFeature.geometry).indexOf("POINT") == -1){		//This is a user drawn shape	
				sndDrawCntReq();												//Update draw counter for royalty returns (if GB and below scale tolerance)
				annoDrawingEnable('selusershape');
				storeUserAnno("rect","");										//Define the unique id for the shape and  number of shapes	
			}else{																//Use the point to define the circle					
				var pointToPass = thecurrentFeature.geometry.getCentroid().clone();	
				annoLayer.removeFeatures(thecurrentFeature);					//need to delete current
				drawRectByCentre(thecurrentFeature.geometry.getCentroid());
			}	
		}else if(document.varform.selectedTool.value == "drawcircle"){;
			//Get the current feature
			var nofeatures = annoLayer.features.length
			var thecurrentFeature = annoLayer.features[nofeatures-1];
			if(String(thecurrentFeature.geometry).indexOf("POINT") == -1){		//This is a user drawn shape	
				sndDrawCntReq();												//Update draw counter for royalty returns (if GB and below scale tolerance)
				annoDrawingEnable('selusershape');
				storeUserAnno("circle","");										//Define the unique id for the shape and  number of shapes	
			}else{																//Use the point to define the circle	
				var pointToPass = thecurrentFeature.geometry.getCentroid().clone();	
				annoLayer.removeFeatures(thecurrentFeature);					//need to delete current
				drawCircleByCentre(thecurrentFeature.geometry.getCentroid());
			}
		}else if(document.varform.selectedTool.value == "drawlabel"){
			sndDrawCntReq();									//Update draw counter for royalty returns (if GB and below scale tolerance)
			annoDrawingEnable('selusershape');
			storeUserAnno("label","");							//Define the unique id for the shape and  number of shapes						
		}
	});
	//Actions after adding new annotation
 	annoLayer.events.register('featuremodified', annoLayer, function(evt) { 
		//Redraw any arrow heads	
		var theSelectedFeature = getTheSelectedAnnoShape();				//Get the selected feature
		var theSelectedFeatureID = theSelectedFeature.attributes.id;			
		var arrowStyle = getArrowStyle(theSelectedFeatureID);
		if(arrowStyle != ""){
			var passedStrokeColour = theSelectedFeature.style.strokeColor.substring(1,theSelectedFeature.style.strokeColor.length);
			removeArrowHeads(theSelectedFeatureID);							//Remove the existing arrow heads
			drawArrowHead(arrowStyle,theSelectedFeature,theSelectedFeatureID,passedStrokeColour);
		}		
		//Update line lengths and areas where necessary
		var theSelFeatureGeometry = theSelectedFeature.geometry;
		if(String(theSelFeatureGeometry).indexOf("POLYGON") != -1){			//Calculate new area of shape and display to user
			var areaString = getAnnoShapeArea(theSelFeatureGeometry);
			if(areaString != ""){
				document.annoform.polyArea.value = areaString;	
			}	
			//Show an width and height for rectangle and radius for circle
			var polyWidth = theSelFeatureGeometry.getBounds().getWidth();
			var polyHeight = theSelFeatureGeometry.getBounds().getHeight();
			var polyRadius = polyWidth/2;
			if(document.getElementById("userrad") != null){
				document.getElementById("userrad").value = polyRadius;
			}
			if((document.getElementById("rectx") != null) && (document.getElementById("recty") != null)){
				document.getElementById("rectx").value = polyWidth;
				document.getElementById("recty").value = polyHeight;
			}	
		}else if(String(theSelFeatureGeometry).indexOf("LINESTRING") != -1){	//Calculate new length of the line and display to user
			var lengthString = getLineLength(theSelFeatureGeometry);	
			if(lengthString != ""){
				document.annoform.lineLen.value = lengthString;	
			}
		}		
	});
	//Actions when selecting anno features
	annoLayer.events.on({
		'featureselected': onFeatureSelect,
		'featureunselected': onFeatureUnselect
	});	
	//Define selection events on the marker layer (Use to show popup)	
	markerLayer.events.on({
   		'featureselected': onMarkerSelect,
    	'featureunselected': onMarkerUnselect
	});				
	//Actions after adding a MasterMap capture shape/fixed extent definition
 	captureLayer.events.register('featureadded', captureLayer, function(evt){ 
		var theCaptureShape = captureLayer.features[captureLayer.features.length-1];		//Get the capture shape	
		var theSelectedFeatureGeometry = String(theCaptureShape.geometry);			
		if(document.varform.selectedTool.value == "capturepoints"){
			selectMultiFixedPoints(theCaptureShape.geometry);
			removeCaptureShape(theCaptureShape);
		}else if((document.varform.selectedTool.value == "historic") || (document.varform.selectedTool.value == "mappack") || (document.varform.selectedTool.value == "osfixed")){		//**DEFINE A FIXED EXTENT
			defineFixedMapExtents(theCaptureShape,"define");			//Define the fixed map extent based around the capture point
		}else{																												//**CAPTURE MASTERMAP SHAPE																												
			if((document.varform.selectedTool.value == "selarea") || (document.varform.selectedTool.value == "selarea2")){				//Define the destination for the captured shape (data extent or user anno)
				var shapeDestination = "anno";
				document.getElementById("mmshapeprogess").style.display = "block";
			}else{
				var shapeDestination = "extent";
				document.getElementById("mmshapeprogess2").style.display = "block";			
			}
			if(theSelectedFeatureGeometry.indexOf("POINT") == 0){
				theSelectedFeatureGeometry = theSelectedFeatureGeometry.substring(6,(theSelectedFeatureGeometry.length-1))		
				var coordArray = theSelectedFeatureGeometry.split(" ");
				var qstring = "centrex=" + coordArray[0] + "&centrey=" + coordArray[1] + "&cid=" + document.varform.cid.value + "&dest=" + shapeDestination;
				var url = "getMMShape.php";
			}else{
				theSelectedFeatureGeometry = theSelectedFeatureGeometry.substring(9,(theSelectedFeatureGeometry.length-2))		
				var qstring = "xtent=" + theSelectedFeatureGeometry + "&cid=" + document.varform.cid.value + "&dest=" + shapeDestination;
				var url = "getMMShapes.php";
			}	
			var mmShapsReq = new ajaxObject(url, handleMMShapesResponse);
			mmShapsReq.update(qstring,'POST');	
		}
		//Remove capture shape
		removeCaptureShape(theCaptureShape);		
	});
 	SVLayer.events.register('featureadded', SVLayer, function(evt) {
		theSVSate = "off";				//Reset the state of marking point
		modifySVControl.activate();
		//Delete the previous marker if there is one
		if(SVLayer.features.length > 1){
			SVLayer.destroyFeatures(SVLayer.features[0]);
		}
		//Initialize the StreetView
		getStreetView();
	});	
	SVLayer.events.register('featuremodified', SVLayer, function(evt) { 
		if(SVLayer.features.length > 0){
			//Get the x-y location of the point
			var theSVLocGeometry = String(SVLayer.features[0].geometry);	
			theSVLocGeometry = theSVLocGeometry.substring(6,(theSVLocGeometry.length-1));	
			//Convert to lat-long (using geotools)
			var tempCoordArray = theSVLocGeometry.split(" ");
			if(document.varform.region.value == "ni"){
				var irish = new GT_Irish();
				irish.setGridCoordinates(tempCoordArray[0],tempCoordArray[1]);
				var wgs84=irish.getWGS84(true);
			}else{
				osgb=new GT_OSGB();
				osgb.setGridCoordinates(tempCoordArray[0],tempCoordArray[1]);
				wgs84 = osgb.getWGS84();
			}
			var theLatLon = new google.maps.LatLng(wgs84.latitude,wgs84.longitude);	
			document.getElementById("panoContent").style.display = "block";
			document.getElementById("panoContainer").style.display = "block"; 
			svService.getPanoramaByLocation(theLatLon, 50, processSVData);
			document.getElementById("panoVisControl").innerHTML = "<a href='javascript:showHideSV();' style='color:#FFFFFF;margin-top:1px;margin-bottom:1px;'>hide</a>";  //Ensure header is correct		
		}
	});
	//Check when the map extent changes - BLOMUrbex imagery available, if large scale maps are available for viewing, total Height and Aerial suppliers and manage fixed points
	map.events.register('moveend', map, function(evt) { 
		//Update the map click counter (if below scale tolerance)
		if((map.getScale() <= clickCountScale) && (document.varform.region.value == "gb")){
			sndClickCntReq();
		}
		if(showBlom == "yes"){			
			//Check for Blom only below this scale and for GB only
			if((map.getScale() <= blomCheckScale) && (document.varform.region.value == "gb")){		
				getBLOMCoverage();
			}
		}
		//Define certain mapping actions for GB mapping based on view scale (MasterMap options, Aerial restriction, 10k mapping choice)			
		if(document.varform.region.value == "gb"){		//Check only below this scale and for GB only
			//Define if MasterMap mapping available (Need to be logged in)
			for (var layindex=0; layindex < document.maplayersform.optBaseLayers.length; layindex++){
				if(document.maplayersform.optBaseLayers[layindex].value == "hybrid"){
					document.maplayersform.optBaseLayers[layindex].disabled = true;					
					if((map.getScale() <= intermediateScaleCheckScale) && (map.getScale() > largeScaleCheckScale) && (document.maplayersform.optBaseLayers[layindex].checked)){	//We are zoomed out one level from where MasterMap is shown - check licensing
						//Define if we are still in a licensed area - if so the MasterMap will stay shown
						checkInLicensedArea();
					}else if(map.getScale() <= largeScaleCheckScale){					//We are zoomed in where MasterMap is shown - check licensing
						if((document.varform.cid.value != "")){  // && (document.varform.mmViewExtents.value == "")){			//Retreive initial licensed areas
							getLicensedAreas();
						}else if(document.varform.cid.value == ""){
							//Show the licensing info
							var outputHTML = "<h3>Switch to detail view?</h3><br/>";
							outputHTML += "<p><a href='javascript:loginForMM();'>Please login first</a></p><br/>";
							outputHTML += "<p>Get a <strong>free view credit</strong> when you <a href='javascript:registerForMM();'>register</a> and with every completed eligible order. <span style='color:#666666;'>(Normally &pound;" + mmLicencePrice + " + VAT)</span></p>"; 
                            outputHTML += "<br /><img src='images/whyOpt1.png' alt='Why opt for detailed mapping?' />";   //style='margin-left:19px;margin-top:3px;' 				
							outputHTML += "<div style='position:absolute;top:5px;right:10px;'><a href='javascript:cancelDetailedPrompt();'>Close [x]</a></div>";
							document.getElementById("previewsInfoContent").innerHTML = outputHTML
							document.getElementById("previewsInfoContent").style.display = "block";
							callCufon();	
						//}else{																							//Check if in a licenced area
						//	checkInLicensedArea();		
						}	
					}else{
						if(document.maplayersform.optBaseLayers[layindex].checked){		//Can't show Mastemap/Hybrid at this map scale swap to Free mapping or Aerial imagery
							toggleMapLayers("gb");
						}
						//Ensure preview request hidden
						document.getElementById("previewsInfoContent").innerHTML = "";
						document.getElementById("previewsInfoContent").style.display = "none";
					}
				}
				//Swap to OS10k if user set up to see 10k
				if((document.maplayersform.optBaseLayers[layindex].value == "gb") && (document.maplayersform.optBaseLayers[layindex].checked)){	//Showing GB street
					if(map.getScale() <= tenKCheckScale){
						if((document.varform.tenkMapType.value == "os10k") && (map.baseLayer.name == "gb")){						//User set up to view 10k and currently showing streetview
							toggleMapLayers("os10k");
						}else{
							if(document.varform.tenkMapType.value == "os10k"){
								//Get licensed areas (if first view) or check if in a current licensed area
								if((document.varform.cid.value != "") && (document.varform.os10kViewExtents.value == "")){
									getOS10kLicensedAreas();	
								}else{
									performOS10kLicenceCheck();
								}
							}
						}	
					}else{
						if((document.varform.tenkMapType.value == "os10k") && (map.baseLayer.name == "os10k")){						//Need to swap from OS10K
							toggleMapLayers("gb");
						}
					}
				}
				if((document.maplayersform.optBaseLayers[layindex].value == "aerial") && (map.getScale() <= aerialCheckScale)){
					//Ensure Aerial cannot be choosen at this scale
					document.maplayersform.optBaseLayers[layindex].disabled = true;
				 	if(document.maplayersform.optBaseLayers[layindex].checked){	//Showing Aerial
						document.maplayersform.optBaseLayers[layindex].checked = false;
						toggleMapLayers("gb");
					}
				}else if((document.maplayersform.optBaseLayers[layindex].value == "aerial") && (map.getScale() > aerialCheckScale)){
					document.maplayersform.optBaseLayers[layindex].disabled = false;			//Ensure Aerial imagery is selectable
				}
			}
		}
		//Fixed product layers (Need updates here to deal with fixed layers for NI!!)
		if(document.varform.region.value == "gb"){	
			//Check if we need to get new selection (No if zooming in)
			var theViewExtent = map.getExtent().toBBOX();
			var theViewExtentArray = theViewExtent.split(",");	
			var newViewWidth = (theViewExtentArray[2] - theViewExtentArray[0]);
			var newViewHeight = (theViewExtentArray[3] - theViewExtentArray[1]);	
			//Check if any of the fixed layers have been initialised - they have not we may need to retrieve the locations on a zoom in
			var fixedLayersDefined = false;	
			for(c=0; c < fixedCheckBoxes.length; c++){	
				if(fixedLayerArray[c] != null){				
					fixedLayersDefined = true;
					break;
				}
			}
			if(((newViewWidth < currentViewWidth) && (newViewHeight < currentViewHeight)) && (fixedLayersDefined)){
				//Zooming in and fixed points are showing - no need to retrieve 
				//Ensure the fixed point check boxes are enabled and user message hides
				updateFixedList(false,true,"block","Check a box to view the fixed point locations on the map.");				
			}else if ((newViewWidth > fixedThresholdSize) && (newViewHeight > fixedThresholdSize)){
				//Current view is bigger than the threshold (too many points to show - so don't)
				//Ensure the fixed point check boxes are disabled and user message shows
				updateFixedList(true,false,"block","Please zoom in to view fixed point information.");	
			}else{
				//Ensure the fixed point check boxes are enabled and user message hides
				updateFixedList(false,true,"block","Check a box to view the fixed point locations on the map.");
				var getFixed = false;
				if((fixedCentreX == null) || (fixedCentreY == null)){
					getFixed = true;
				}else{
					if(Math.sqrt((fixedCentreX - map.getCenter().lon) * (fixedCentreX - map.getCenter().lon)) > fixedBufferDistance){
						getFixed = true;
					}
					if(Math.sqrt((fixedCentreY - map.getCenter().lat) * (fixedCentreY - map.getCenter().lat)) > fixedBufferDistance){
						getFixed = true;
					}
				}	
				if(getFixed){
					var theClassCodes = getFixedClassCodes();		//Get class codes from the check box states		
					if(theClassCodes != ""){
						var theClassCodesArray = theClassCodes.split("|");
						for(c=0; c < theClassCodesArray.length; c++){			//Loop through each fixed layer class code and add to map if selected
							if(theClassCodesArray[c] != ""){			
								var qstring = "extent=" + theViewExtent + "&classcode=" + theClassCodesArray[c] + "&buffer=" + fixedBufferDistance;		
								addFixed(qstring, c);
							}else{
								if(fixedLayerArray[c] != null){					//Ensure the fixed layer is removed before adding
									map.removeLayer(fixedLayerArray[c]);
									fixedLayerArray[c] = null;
								}
							}			
						}	
					}else{														//No layers showing - ensure  all fixed layers are removed
						for(c=0; c < fixedCheckBoxes.length; c++){				//Loop through each fixed layer class code and add to map if selected
							if(fixedLayerArray[c] != null){				
								map.removeLayer(fixedLayerArray[c]);
								fixedLayerArray[c] = null;
							}			
						}				
					}			
					//Store the center point that the Fixed points were retrieved from
					fixedCentreX = map.getCenter().lon;
					fixedCentreY = map.getCenter().lat;
				}			
			}			
			//Show the fixed points as an overlay
			if(document.varform.productoption.value == "fixed"){
				if(((newViewWidth < currentViewWidth) && (newViewHeight < currentViewHeight)) && (fixedLayer != null)){
					//Zooming in and fixed points are showing - no need to retrieve 				
				}else if ((newViewWidth > fixedThresholdSize) && (newViewHeight > fixedThresholdSize)){
					//Current view is bigger than the threshold (too many points to show - so don't)
					//Destroy the fixed product overlay layer if one exists
					if(fixedLayer != null){
						fixedLayer.destroy();
						fixedLayer = null;
					}
					showDialog('Warning','Please zoom in to view extent of this product on the map.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
				}else{
					var getFixed = false;
					if((fixedBuyCentreX == null) || (fixedBuyCentreY == null)){
						getFixed = true;
					}else{
						if(Math.sqrt((fixedBuyCentreX - map.getCenter().lon) * (fixedBuyCentreX - map.getCenter().lon)) > fixedBufferDistance){
							getFixed = true;
						}
						if(Math.sqrt((fixedBuyCentreY - map.getCenter().lat) * (fixedBuyCentreY - map.getCenter().lat)) > fixedBufferDistance){
							getFixed = true;
						}
					}	
					if(getFixed){
						showFixedProducts();			
						//Store the center point that the Fixed points were retrieved from
						fixedBuyCentreX = map.getCenter().lon;
						fixedBuyCentreY = map.getCenter().lat;
					}
				}
			}
			//Store the current map width and height
			currentViewWidth = newViewWidth;
			currentViewHeight = newViewHeight;
		}
	});	
	//Need to ensure that the passed data set shows as selected
	if(selectedData != ""){
		if(passedExtent != ""){						//Extent has been set so user is not prompted when the extent is redrawn
			redrawingExtent = true;
		}
		getProductInfo(selectedData,"reorder");			//Select the passed product	- extent and anno will then be drawn
	}
	//Make the slider invisible (for some reason not working if not not initialized visible)
	if(document.getElementById("slider2") != null){
		document.getElementById("slider2").style.display = "none";	
	}
}
//****************Change the base mapping region ('gb' or 'ni')
function changeMappingRegion(newMapRegion,theType,theAction){
	//Check if we need to prompt
	selectedIndex = getSelectedProductIndex();
	if((annoLayer.features.length == 0) && (extentLayer.features.length == 0) && (theAction == "prompt") && (selectedIndex == -1)){		//No anno or extents draw - just change it
		theAction = "change";
	}
	if(theAction == "prompt"){				//Routine called to promt to change mapping
		var dialogContent = "This will remove any selected products, data areas and user annotations. Do you want to continue?<br/><br/><input type='button' value='Yes' id='yesButton' onclick='changeMappingRegion(\"" + newMapRegion + "\",\"" + theType + "\",\"change\");'>  <input type='button' value='No' id='noButton' onclick='changeMappingRegion(\"" + newMapRegion + "\",\"" + theType + "\",\"reset\");' >"
		showDialog('',dialogContent,'prompt');
	}else if(theAction == "change"){		//Routine called to actually change mapping	
		hideDialog();			
		document.varform.region.value = newMapRegion; 				//Set new region
		document.varform.data.value = "";							//Clear selected data
		document.varform.action = "map.php";
		document.varform.submit();
	}else if(theAction == "reset"){										//**Reset
		hideDialog();
		if(theType == "radio"){			//Radio buttons
			if(document.searchform.orderType[0].checked){
				document.searchform.orderType[0].checked = false;
				document.searchform.orderType[1].checked = true;
			}else{
				document.searchform.orderType[0].checked = true;
				document.searchform.orderType[1].checked = false;
			}
		}
	}		
}
//****************Change the mapping layer that shows (Free mapping, Aerial Images, MasterMap, Hybrid) - Called from popup after map search
function toggleMapLayers1(passedLayer){
	hideSearchOptions();														//Hide options layer
	if(passedLayer == "hybrid"){						//If hybrid zoom in to a zoom level in which hybrid mapping shows (250m)
		zoomToPoint(map.getCenter().lon,map.getCenter().lat,250,"");
	}else{											//Show the passed layer
		toggleMapLayers(passedLayer);
	}
}
//****************Change the mapping layer that shows (Free mapping, Aerial Images, MasterMap, Hybrid)
function toggleMapLayers(passedLayer){
	//Get the state (disabled or not) of the radio buton to define if we can show this layer
	var changeTheLayer = true;
	for (var i=0; i < document.maplayersform.optBaseLayers.length; i++){	
		if(document.maplayersform.optBaseLayers[i].value == passedLayer){
			if(document.maplayersform.optBaseLayers[i].disabled){		
				changeTheLayer = false;
			}
			break;	
		}
	}	
	//If user clicks on the hybrid layer when disabled - assume they want to see it so need to zoom in if necessary
	if((changeTheLayer == false) && (passedLayer == "hybrid")){
		if(map.getZoom() <= 11){	
			map.zoomTo(12);
		}
	}else{
		if((passedLayer == "aerial") && (mmLayer.getVisibility())){
			changeOpacity(10);
			hideMapLayers();
			slider1.setValue(10);
		}
		if(changeTheLayer){
			//Initially hide opacity options
			document.getElementById("slider2").style.display = "none";	
			if(passedLayer == "hybrid"){
				//Toggle for MasterMap may be active at the scale above the largescale treshold - so need a licese check to stop user viewing un licensed mapping 
				if((map.getScale() <= intermediateScaleCheckScale) && (map.getScale() > largeScaleCheckScale) && (document.maplayersform.optBaseLayers[i].checked)){	//We are zoomed out one level from where MasterMap is shown - check licensing
					//Define if we are still in a licensed area - if so the MasterMap will stay shown					
					if(document.varform.isRetailOutlet.value == "no"){							//If not a retail outlet need to check we are still in a licensed arae
						checkInLicensedArea();
					}
				}else{
					//Turn on the MasterMap layer 
					mmLayer.setVisibility(true);			
					//Set opacity of the base layers to 0 to ensure MM does not draw over the base layer and look ugly
					baseLayer.setOpacity(0);
					base10kLayer.setOpacity(0);
					aerialLayer.setOpacity(0);
					mmLayer.setOpacity(1);											//Set default opacity for mastermap layer
					document.getElementById("slider2").style.display = "block";	//Show opacity options
					slider1.setValue(0);										//Set initial slider pos
				}				
			}else{
				//Ensure opacity is set to 1
				baseLayer.setOpacity(1);
				if(base10kLayer != null){
					base10kLayer.setOpacity(1);
				}
				aerialLayer.setOpacity(1);
				//Hide MasterMap layer
				mmLayer.setVisibility(false);	
				//Assign new base layer
				var newBaseLayer = null;
				var layerArray = map.layers;
				for (c=0; c < layerArray.length;c++){
					if(layerArray[c].name == passedLayer){
						newBaseLayer = layerArray[c];
						break;
					}
				}
				if(newBaseLayer != null){
					map.setBaseLayer(newBaseLayer)
				}
			}	
			//Ensure this radio button is selected
			for (var i=0; i < document.maplayersform.optBaseLayers.length; i++){	
				if(document.maplayersform.optBaseLayers[i].value == passedLayer){
					document.maplayersform.optBaseLayers[i].checked = true;		
					break;	
				}
			}
			//Hide the map layers tab
			hideMapLayers();
		}			
	}
}
//****************Change opacity of the overlay layer of the hybrid map
function changeOpacity(pos){
	var opacityValue = (10-pos)/10;	
	if((opacityValue < 1) && (map.baseLayer.name != "aerial")){     //First initiation of hybrid
		map.setBaseLayer(aerialLayer);
		aerialLayer.setOpacity(1);		
		var newOpacity = opacityValue; 								//Set the opacity of MasterMap
		mmLayer.setOpacity(newOpacity);	
		//Record Aerial imagery viewed for royalty purposes
		recordGMView();
	}else{
		var newOpacity = opacityValue;  								//Set the opacity of MasterMap
		mmLayer.setOpacity(newOpacity);
	}
}
//****************Check if a Getmapping view needs recording
function recordGMView(){
	if(slider1.getValue() > 0){									//Aerial imagery is showing.
		//Get map centre
		var mapCentrePoint = map.getCenter();
		//Get the map extent
		var viewExtent = map.getExtent().toBBOX();		
		//Create geometry of centre and extent to check intersections with the licensed areas
		var theExtentArray = viewExtent.split(",");	
		var pointList = [];
		var newPoint = new OpenLayers.Geometry.Point(theExtentArray[0],theExtentArray[1]);
		pointList.push(newPoint);
		var newPoint = new OpenLayers.Geometry.Point(theExtentArray[0],theExtentArray[3]);
		pointList.push(newPoint);
		var newPoint = new OpenLayers.Geometry.Point(theExtentArray[2],theExtentArray[3]);
		pointList.push(newPoint);
		var newPoint = new OpenLayers.Geometry.Point(theExtentArray[2],theExtentArray[1]);
		pointList.push(newPoint);
		var newPoint = new OpenLayers.Geometry.Point(theExtentArray[0],theExtentArray[1]);
		pointList.push(newPoint);					
		var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
		var theViewExtentGeom = new OpenLayers.Geometry.Polygon([linearRing]);
		var theViewCentreGeom = new OpenLayers.Geometry.Point(mapCentrePoint.lon,mapCentrePoint.lat);
		//Loop thru all the licensed area to check if map centre intersects
		storeRoyalty = false;
		for(p=0; p < licensedLayer.features.length;p++){
			var centreIntersection = licensedLayer.features[p].geometry.intersects(theViewCentreGeom);
			if(centreIntersection){														//***Centre intersects a licensed area - quit loop and run script to store the royalty
				storeRoyalty = true;		
				break;	
			}
		}
		if(storeRoyalty){
			var qstring = "centrex=" + map.getCenter().lon + "&centrey=" + map.getCenter().lat + "&vxtent=" + map.getExtent().toBBOX() + "&site=" + document.varform.thesite.value + "&licenceID=" + licensedLayer.features[p].attributes.id;			
			gmCountReq = new ajaxObject('gmRoyalty.php', handleClickCntResponse);
			gmCountReq.update(qstring,'POST');
		}	
	}			
}
//****************Update map scale (USED FOR TESTING)
function updateMapScale(){
	var theScale = Number(document.varform.theMapScale.value);
	if(theScale != 0){
		map.zoomToScale(theScale,false);
	}
}
//****************Shows the map layers tab
function showMapLayers(toShow){
	toolbox.slideOut();
	document.getElementById("mapLayersContainer").style.display = "block";
	showMapLayerOptions(toShow);		
}
//****************Hides the map layers tab
function hideMapLayers(){
	document.getElementById("mapLayersContainer").style.display = "none";
}
//****************Shows the specific option in the map layers tab
function showMapLayerOptions(toShow){
	for(c=0;c < mapLayerOptions.length;c++){
		if(mapLayerOptions[c] == toShow){			
			document.getElementById(mapLayerOptions[c]).style.display = "block";
		}else{
			document.getElementById(mapLayerOptions[c]).style.display = "none";
		}	
	} 
}
//-------------------------------------------------------------------------FIXED LAYER SCRIPTS

//**************************Ensure the Fixed layer check boxes are enabled/disabled and user message shows/hides on zooming in and out
function updateFixedList(checkDisabled,layerVis,messageState,theMessage){
	for(c=0; c < fixedCheckBoxes.length; c++){	
		var theCheckBox = document.getElementById(fixedCheckBoxes[c]);
		if(theCheckBox != null){				
			theCheckBox.disabled = checkDisabled;
			if(theCheckBox.checked){						//If poi layer is turned one ensure the map layer shows/hides
				if(fixedLayerArray[c] != null){
					fixedLayerArray[c].setVisibility(layerVis);
				}						
			}
		}	
		//Toogle the colour of the check box labels
		var theLabelName = fixedCheckBoxes[c].replace("chk","lbl");
		if(checkDisabled){				//Make light grey
			document.getElementById(theLabelName).style.color = "#cccccc";
		}else{							//Make dark grey
			document.getElementById(theLabelName).style.color = "#ffffff";		
		}
			
	}	
}
//**************************Get list of class codes from the check box states
function getFixedClassCodes(){
	var theClassCodes = "";
	var classCodeCount = 0;
	for(c=0; c < fixedCheckBoxes.length; c++){	
		var theCheckBox = document.getElementById(fixedCheckBoxes[c]);
		if(theCheckBox.checked){											//Add value to list		
			classCodeCount += 1;
			if(classCodeCount == 1){
				theClassCodes = theCheckBox.value;
			}else{
				theClassCodes += "|" + theCheckBox.value;
			}
		}else{																//Add nothing to list (ie not checked)
			classCodeCount += 1;
			if(classCodeCount == 1){
				theClassCodes = "";
			}else{
				theClassCodes += "|" + "";
			}
		}
	}
	return theClassCodes;						//Return list of the selected layers
}
//**************************Update Fixed Points - called when checkbox turned on-off
function updateFixed(theCheckBox,fixedLayerIndex){
	if(theCheckBox.checked){		//Turn this layer on
		//Check how many fixed layers layers are selected
		var testclassCodeCount = -1;
		for(c=0; c < fixedCheckBoxes.length; c++){				
			var theTestCheckBox = document.getElementById(fixedCheckBoxes[c]);
			if(theTestCheckBox.checked){											//Add value to list
				testclassCodeCount += 1;			
			}
		}	
		if(testclassCodeCount == 3){
			showDialog('Warning','We are only able to display 3 fixed point overlays at any one time.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			theCheckBox.checked = false;
		}else{
			if(fixedLayerArray[fixedLayerIndex] != null){				//Layer exists - therefore just make visible
				fixedLayerArray[fixedLayerIndex].setVisibility(true);
			}else{													//Layer does not exists - therefore retrieve data for it
				var theViewExtent = map.getExtent().toBBOX();
				var theViewExtentArray = theViewExtent.split(",");	
				var newViewWidth = (theViewExtentArray[2] - theViewExtentArray[0]);
				var newViewHeight = (theViewExtentArray[3] - theViewExtentArray[1]);	
				if((newViewWidth > fixedThresholdSize) && (newViewHeight > fixedThresholdSize)){
					//Current view is bigger than the threshold (too many points to show - so don't)
				}else{
					var qstring = "extent=" + theViewExtent + "&classcode=" + theCheckBox.value + "&buffer=" + fixedBufferDistance;
					addFixed(qstring,fixedLayerIndex);
					//Store the center point that the fixed points were retrieved from
					fixedCentreX = map.getCenter().lon;
					fixedCentreY = map.getCenter().lat;
				}
			}
		}
	}else{
		if(fixedLayerArray[fixedLayerIndex] != null){				//Layer exists - therefore just make invisible
			fixedLayerArray[fixedLayerIndex].setVisibility(false);
		}
	}
	//Hide the map layers tab
	hideMapLayers();		
}
//**************************Retrieve Fixed points from database and add to layer
function addFixed(qstring,fixedLayerIndex){
	//Ensure the Fixed layers are removed before adding
	if(fixedLayerArray[fixedLayerIndex] != null){
		fixedLayerArray[fixedLayerIndex].destroy();
		fixedLayerArray[fixedLayerIndex] = null;
		//Remove any popups showing
		if(feature != null){
			if (feature.popup) {
				popup.feature = null;
				map.removePopup(feature.popup);
				feature.popup.destroy();
				feature.popup = null;
			}
		}
	}
	//Add the Fixed layer
	//Get the location of script to retrieve the fixed points
	if(String(window.location).indexOf("map.php") != -1){
		var basePath = String(window.location).substring(0,(String(window.location).length - 8));
	}else{
		var basePath = String(window.location);
	}
	if(basePath.substring((basePath.length-1),basePath.length ) != "/"){
		basePath = basePath + "/";
	}
	var fixedScriptPath = basePath + "getFixed.php?"; 
	var fixedScript = fixedScriptPath + qstring + "&layerindex= " + fixedLayerIndex;
	fixedLayerArray[fixedLayerIndex] = new OpenLayers.Layer.GML("FIXED_" + String(fixedLayerIndex), fixedScript, { format: OpenLayers.Format.Text});
	map.addLayer(fixedLayerArray[fixedLayerIndex]);
	//Define the visible Fixed layers
	var visibleLayers = new Array();
	var visLayCnt = -1;
	for(c=0; c < fixedCheckBoxes.length; c++){
		if(fixedLayerArray[c] != null){
			visLayCnt += 1;				
			visibleLayers[visLayCnt] = fixedLayerArray[c];
		}			
	}	
	visLayCnt += 1;
	visibleLayers[visLayCnt] = markerLayer;										//Ensure the maker layer is still selectable
	if(fixedLayer != null){
		visLayCnt += 1;
		visibleLayers[visLayCnt] = fixedLayer;										//Ensure the fixed product layer is still selectable
	}
	//Add a select feature control for the visible Fixed point layers
	selFeatureControl = new OpenLayers.Control.SelectFeature(visibleLayers); 
 	map.addControl(selFeatureControl);
	selFeatureControl.activate();
	//Define selection events on the fixed layer	
	fixedLayerArray[fixedLayerIndex].events.on({
    'featureselected': onFixedFeatureSelect,
    'featureunselected': onFixedFeatureUnselect
	});	
}
//**************************Unselect feature on popup close
function onPopupClose(evt) {
	selFeatureControl.unselect(this.feature);
}
//**************************Show popup on feature select
function onFixedFeatureSelect(evt) {
    //Get geometry and layer index of selected feature
    feature = evt.feature
    var testinGeom = feature.geometry;
	var tempArray = feature.attributes.description.split("~");
	var theCurrentLayIndex = Number(tempArray[2]);    //0=description, 1=feature ID, 2=layer index	
	//Define if any other points have the same geometry - store attributes in an array   
   	var passedDescriptionArray = new Array();
	for(p=0; p < fixedLayerArray[theCurrentLayIndex].features.length;p++){
		var centreIntersection = fixedLayerArray[theCurrentLayIndex].features[p].geometry.equals(testinGeom);			
		if(centreIntersection){													
			 passedDescriptionArray.push(fixedLayerArray[theCurrentLayIndex].features[p].attributes.description)
		}
	}  
   	//Get the popup content
   	var popupContent = "";
   	for(c=0; c < passedDescriptionArray.length;c++){  
   		var tempDescArray = passedDescriptionArray[c].split("~");    //0=description, 1=feature ID
   		popupContent +=	"<h3>"+feature.attributes.title + "</h3>" + tempDescArray[0];
   	}
    //feature = evt.feature; 	
	//var passedDescription = feature.attributes.description;
	//var featureDescArray = passedDescription.split("~");    //0=description, 1=feature ID
    popup = new OpenLayers.Popup.FramedCloud("featurePopup",
                             feature.geometry.getBounds().getCenterLonLat(),
                             new OpenLayers.Size(100,100),
                             popupContent,	 
							// "<h3>"+feature.attributes.title + "</h3>" +
                             //featureDescArray[0],
                             null, true, onPopupClose);
    popup.autosize = true;
	popup.panMapIfOutOfView = false;
	feature.popup = popup;		
    popup.feature = feature;
    map.addPopup(popup);
	callCufon();		
}
//**************************Destroy popup on feature unselect
function onFixedFeatureUnselect(evt) {
    feature = evt.feature;
    if (feature.popup) {
        popup.feature = null;
        map.removePopup(feature.popup);
        feature.popup.destroy();
        feature.popup = null;
    }
}

//-------------------------------------------------------------------------BLOMURBEX SCRIPTS
//****************Define if current view in an available BLOMUrbex coverage area
function getBLOMCoverage(){	
	var qstring = "centrex=" + map.getCenter().lon + "&centrey=" + map.getCenter().lat + "&vxtent=" + map.getExtent().toBBOX();
	var blomReq = new ajaxObject('getBlomCoverage.php', handleBLOMResponse);
	blomReq.update(qstring,'POST');			
}
//****************Handles the response from getting BLOMUrbex coverage
function handleBLOMResponse(responseText, responseStatus){
	if(responseStatus == 200){
		var response = trim(responseText);
		if(response.substring(0,3) == "yes"){				//In covearge area
			document.getElementById('blomLink').src = "http://shop.centremapslive.co.uk/images/btnBlomON.png";		
		}else if(response.substring(0,7) == "pending"){			//In captured area
			document.getElementById('blomLink').src = "http://shop.centremapslive.co.uk/images/btnBlom.png";		
		}else{												//Not available area
			document.getElementById('blomLink').src = "http://shop.centremapslive.co.uk/images/btnBlom.png";		
		}
	}
}
//****************Emails Blom info request to site admin
function sendBlomReq(){
	if(document.varform.cid.value != ""){							//Check user is logged in
		var qstring = "thecid=" + document.varform.cid.value + "&cx=" + map.getCenter().lon + "&cy=" + map.getCenter().lat;	
		var blomReq = new ajaxObject('blom_request.php', handleBlomReqResponse);
		blomReq.update(qstring,'POST');	
	}else{
		showDialog('Warning','Please ensure you are logged in before sending the request.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
	}
}
//****************Handles the response from  Blom info request
function handleBlomReqResponse(responseText, responseStatus){
	if(responseStatus == 200){
		if(responseText == "yes"){														
			showDialog('Success','A request for more information has been sent to ' + document.varform.thesitename.value + '.<br/>You will be emailed with a response soon.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','success');									
		}else{
			showDialog('Error','Request could not be sent. Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');									
		}		
	}
}
//****************Define action when user click on the BLOM LINK
function gotoBlom(){
	if(document.getElementById('blomLink').src == "http://shop.centremapslive.co.uk/images/btnBlomON.png"){				//In covearge area		
		//Open in new window;
		theURL =  "http://shop.centremapslive.co.uk/blomURBEX/urbexLIC/index.php?easting=" + map.getCenter().lon + "&northing=" + map.getCenter().lat;
		winName = "oblique";
		features = "menubar=yes,toolbar=yes,scrollbars=yes,resizable=yes,width=900,height=700";
		var theWin = window.open(theURL,winName,features);		
		theWin.focus();									
	}else{												//Not available area or in captured are
		sendBlomReq();		
	}
}

//-------------------------------------------------------------------------MASTERMAP LICENSING SCRIPTS

//****************Send request for all licensed areas
function getLicensedAreas() {
	var qstring = "&cid=" + document.varform.cid.value + "&companyid=" + document.varform.companyid.value + "&vxtent=" + map.getExtent().toBBOX();	
	if(getPreviewsReq != null){
		getPreviewsReq.abort();
	}
	//licensedLayer.destroyFeatures();												//Delete features from the layer first
	getPreviewsReq = new ajaxObject('getLicensedAreas.php', handleGetLicensedAreasResponse);
	getPreviewsReq.update(qstring,'POST');
}
//****************Handles the response from getting all licensed areas
function handleGetLicensedAreasResponse(responseText, responseStatus){
	if(responseStatus == 200){
		if(responseText != ""){																//Check data returned
			if(responseText.indexOf('_' != -1)) {
				var thePreviewInfo = responseText.split('_');
				var numberFound = thePreviewInfo[0];
				var prevExtents = thePreviewInfo[1].split('|');
				var prevIDS = thePreviewInfo[2].split('|');
				var prevNames = thePreviewInfo[3].split('|');
				var prevDates = thePreviewInfo[4].split('|');				
				var newExpireDate = getPreviewExpireyDate(new Date(),"new");					//Get expiry date
				//Flag we have performed the initial license check
				document.varform.mmViewExtents.value = numberFound;						
				//Draw extents to the map (invisible)
				if(Number(numberFound) > 0){
					for(n=0;n<Number(numberFound);n++){
						//Check if licensed area already drawn to interface
						var isNewArea = true;
						if(licensedLayer.features.length > 0){
							for(p=0; p < licensedLayer.features.length;p++){
								if(prevIDS[n] == licensedLayer.features[p].attributes.id){
									isNewArea = false;
									break;
								}
							}
						}
						if(isNewArea){									
							var geomString = prevExtents[n].substring(9,(prevExtents[n].length-2));
							drawLicenseExtent(geomString,prevIDS[n],prevNames[n],prevDates[n],"OSMM"); 
						} 
					}
				}	
				//Check if in licenced area				
				addURMcoverage();			//Firstly define if the area is urban-rural-moorland						
			}else{
				var outputHTML = "<h3>Licensing Info</h3>";
				outputHTML += "<p class='error'>An error has occured checking OS MasterMap licensed areas.</p>";
				outputHTML += "<div style='position:absolute;top:5px;right:10px;'><a href='javascript:cancelDetailedPrompt();'>Close [x]</a></div>";								
				//Show the licensing info
				document.getElementById("previewsInfoContent").innerHTML = outputHTML
				document.getElementById("previewsInfoContent").style.display = "block";
				callCufon();
			}
		}else{
			var outputHTML = "<h3>Licensing Info</h3>";
			outputHTML += "<p class='error'>An error has occured checking OS MasterMap licensed areas.</p>";
			outputHTML += "<div style='position:absolute;top:5px;right:10px;'><a href='javascript:cancelDetailedPrompt();'>Close [x]</a></div>";						
			//Show the licensing info
			document.getElementById("previewsInfoContent").innerHTML = outputHTML
			document.getElementById("previewsInfoContent").style.display = "block";
			callCufon();
		}		
	}
}
//****************Close the MasterMap preview info window
function closePreviewsInfoContent(){
	document.getElementById("previewsInfoContent").style.display = "none";
}
//****************Cancels the detailed mapping options
function cancelDetailedPrompt(){
	document.getElementById("previewsInfoContent").style.display = "none";
	if(map.getZoom() > 11){			
		//Need to reduce the OS MasterMap count by 1
		theBaseData = "OS MasterMap";
		var qstring = "maptype=" + theBaseData + "&centrex=" + map.getCenter().lon + "&centrey=" + map.getCenter().lat + "&vxtent=" + map.getExtent().toBBOX() + "&site=" + document.varform.thesite.value;;					
		clickCountReq = new ajaxObject('mapclick_dec.php', handleClickCntResponse2);
		clickCountReq.update(qstring,'POST');
	}
}
//****************Show MasterMap data
function showLicensedArea(){
	enableMasterMap();
	toggleMapLayers("hybrid");
	closePreviewsInfoContent();
}
//****************Enables the MasterMap hybrid check box (called when not in a licensed area)
function enableMasterMap(){
	for (var e=0; e < document.maplayersform.optBaseLayers.length; e++){	
		if(document.maplayersform.optBaseLayers[e].value == "hybrid"){
			document.maplayersform.optBaseLayers[e].disabled = false;
			break
		}
	}
}
//****************Add new MasterMap license area
function createNewLiceseArea(licSize){
	//Check reference has been added
	if(document.varform.isRetailOutlet.value == "yes"){
		var thePrevRef = "outlet-" + Math.round(map.getCenter().lon) + "-" + Math.round(map.getCenter().lat);
	}else{
		var thePrevRef = document.getElementById("mmpreviewref").value;
	}	
	if((thePrevRef.indexOf("_") != -1) || (thePrevRef.indexOf("|") != -1) || (thePrevRef.indexOf(",") != -1)){
		showDialog('Warning','Please ensure the name does not contain "|", "," or "_" characters.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');		
	}else if((thePrevRef == "Add a reference") || (thePrevRef == "")){
		showDialog('Warning','Please add your own unique reference.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');	
	}else{
		//Get the user's current credit
		var qstring = "cid=" + document.varform.cid.value + "&compid=" + document.varform.companyid.value + "&licsize=" + licSize;	
		if(getCreditReq != null){
			getCreditReq.abort();
		}
		getCreditReq = new ajaxObject('getViewCredit.php', handleGetViewCreditResponse1);
		getCreditReq.update(qstring,'POST');			
	}
}
//****************Handles the response from licensing an area
function handleStorePreviewResponse(responseText, responseStatus){
	if(responseStatus == 200){		
		if(responseText != ""){
			responseText = trim(responseText);
			var responseArray = responseText.split("|");
			if(responseArray[0] == "yes"){
				drawLicenseExtent(responseArray[1],responseArray[2],responseArray[3],responseArray[4],"OSMM");  
				enableMasterMap();
				toggleMapLayers("hybrid");				//Draw mastermap
				closePreviewsInfoContent();				//Hide info
				if(responseArray[7] == "no"){				
					if((responseArray[5] != -1) && (responseArray[6] != -1)){			//Update the available credits on the page
						document.varform.currentViewCredit.value = responseArray[5]; 
						document.varform.currentFreeViewCredit.value = responseArray[6]; 
					}
				}			
			}		
		}
	}
}
//****************Handles the response from getting user's available credit before buying a new area
function handleGetViewCreditResponse1(responseText, responseStatus){
	if(responseStatus == 200){		 
		responseText = trim(responseText);
		var tempArray = responseText.split("|");
		var currentCredit = tempArray[0];
		document.varform.currentViewCredit.value = currentCredit; //Update the available credit on the page
		var isInvoiceCustomer = tempArray[3];
		var licSize = tempArray[4];
		var currentFreeCredit = tempArray[5];
		document.varform.currentFreeViewCredit.value = currentFreeCredit; //Update the available credit on the page
		var currentCreditTotal = Number(currentCredit) + Number(currentFreeCredit);		
		requestNewLiceseArea(true,currentCreditTotal,licSize,isInvoiceCustomer);	
	}
}
//****************Define the actions when requesting a new licence (Store the licence or prompt to add credit) 
function requestNewLiceseArea(requestIt,currentCredit,licSize,isInvoiceCustomer){
	if(requestIt){
		hideDialog();
		if(document.varform.isRetailOutlet.value == "yes"){
			var thePrevRef = "outlet-" + Math.round(map.getCenter().lon) + "-" + Math.round(map.getCenter().lat);
		}else{
			var thePrevRef = document.getElementById("mmpreviewref").value;
		}			
		if((Number(currentCredit) < Number(mmLicencePrice)) && (document.varform.isRetailOutlet.value != "yes")){    
			//Not enough credit, prompt to add credit or invoice for
			var outputHTML = "<h3>Licensing Info</h3><br/>";
			outputHTML += "<p class='error'><strong>Insufficient view credits found.</strong></p>";
			//Define if the full charge is to be invoiced or balance fro existing credits			
			var theAmountToInvoice = (Number(mmLicencePrice) - Number(currentCredit));
			if(Number(theAmountToInvoice) == Number(mmLicencePrice)){
				var invoiceType = "invoice";
			}else{
				var invoiceType = "partinvoice";
			}
			if(isInvoiceCustomer == "yes"){
				outputHTML += "<form name='creditform' id='creditform' action='' method='post'><table cellspacing='3' cellpadding='0'><tr><td><p>Accept &pound;" +  formatPrice(Math.round(theAmountToInvoice*100)/100) + " + VAT for this order</p></td><td><strong><a href='javascript:invoiceNewLiceseArea(\"" + thePrevRef + "\",\"" + licSize + "\",\"" + invoiceType + "\");'>Add to invoice</a></strong></td></tr>"; 
				if(document.varform.islitesite.value != "yes"){
					outputHTML += "<tr><td style='padding-top:5px;'><p>Pre-pay for credit by card (min. &pound;5)   &pound;<input name='addcredit' id='addcredit' type='text' size='3' value='5'></p></td><td style='padding-top:5px;'><strong><a href='javascript:addViewCredit(\"creditform\");'>Add Credit </a></strong></td></tr>";
				}
				outputHTML += "</table></form>";
			}else{
				if(document.varform.islitesite.value != "yes"){
					outputHTML += "<form name='creditform' id='creditform' action='' method='post'><p><br/>Pre-pay for credit by card (min. &pound;5)   &pound;<input name='addcredit' id='addcredit' type='text' size='3' value='5'>&nbsp;&nbsp;&nbsp;<strong><a href='javascript:addViewCredit(\"creditform\");'>Add Credit </a></strong></p></form>";
				}else{
					outputHTML += "<p class='error'><em>Adding credit not available</em></p>";
				}
			}
			outputHTML += "<div style='position:absolute;top:5px;right:10px;'><a href='javascript:cancelDetailedPrompt();'>Close [x]</a></div>";						
			document.getElementById("previewsInfoContent").innerHTML = outputHTML;
			document.getElementById("previewsInfoContent").style.display = "block";
			callCufon();
		}else{
			//Store the licensed area
			var thePayAction = "credit";	
			var qstring = "prevref=" + thePrevRef + "&cid=" + document.varform.cid.value + "&centrex=" + map.getCenter().lon + "&centrey=" +  map.getCenter().lat + "&vxtent=" + map.getExtent().toBBOX() + "&lictype=new&passeddate=&payaction=" + thePayAction + "&compid=" + document.varform.companyid.value + "&licsize=" + licSize + "&isretailoutlet=" + document.varform.isRetailOutlet.value;		
			storePreviewReq = new ajaxObject('storeMMPreview.php', handleStorePreviewResponse);
			storePreviewReq.update(qstring,'POST');
		}							
	}else{
		hideDialog();
	}
}
//****************Store a new MasterMap license area which will be invoiced for
function invoiceNewLiceseArea(thePrevRef,licSize,thePayAction){
	//Store the licensed area	
	var qstring = "prevref=" + thePrevRef + "&cid=" + document.varform.cid.value + "&centrex=" + map.getCenter().lon + "&centrey=" +  map.getCenter().lat + "&vxtent=" + map.getExtent().toBBOX() + "&lictype=new&passeddate=&payaction=" + thePayAction + "&compid=" + document.varform.companyid.value + "&licsize=" + licSize;		
	storePreviewReq = new ajaxObject('storeMMPreview.php', handleStorePreviewResponse);
	storePreviewReq.update(qstring,'POST');
}
//****************Extends a new MasterMap license area which will be invoiced for
function invoiceExtendLiceseArea(thePrevRef,theLicDate,licSize,thePayAction){
	//Store the licensed area
	var qstring = "prevref=" + thePrevRef + "&cid=" + document.varform.cid.value + "&centrex=" + map.getCenter().lon + "&centrey=" +  map.getCenter().lat + "&vxtent=" + map.getExtent().toBBOX() + "&lictype=extend&passeddate=" + theLicDate + "&payaction=" + thePayAction + "&compid=" + document.varform.companyid.value + "&licsize=" + licSize;		
	storePreviewReq = new ajaxObject('storeMMPreview.php', handleStorePreviewResponse);
	storePreviewReq.update(qstring,'POST');
}
//****************Extends a MasterMap license area
function extendArea(licDate,licName,licSize){	
	//Define name for the extension
	if(document.varform.isRetailOutlet.value == "yes"){
		if(licName.indexOf(": extension") == -1){
			var suffixToAdd = "extension";
		}else{
			var suffixToAdd = "";
		}
	}else{
		var suffixToAdd = document.getElementById("mmpreviewrefsuffix").value;
	}
	if(suffixToAdd != ""){
		licName = licName + ": " + suffixToAdd;
	}
	//Get the user's current credit first
	var qstring = "cid=" + document.varform.cid.value + "&licName=" + licName +"&licDate=" + licDate + "&compid=" + document.varform.companyid.value + "&licsize=" + licSize;	
	if(getCreditReq != null){
		getCreditReq.abort();
	}
	getCreditReq = new ajaxObject('getViewCredit.php', handleGetViewCreditResponse2);
	getCreditReq.update(qstring,'POST');
}
//****************Handles the response from getting user's available credit before extending an area
function handleGetViewCreditResponse2(responseText, responseStatus){
	if(responseStatus == 200){		 
		responseText = trim(responseText);
		var tempArray = responseText.split("|");
		var currentCredit = tempArray[0];
		document.varform.currentViewCredit.value = currentCredit; //Update the available credit on the page
		var thePrevRef = tempArray[1];
		var theLicDate = tempArray[2];
		var isInvoiceCustomer = tempArray[3];
		var licSize = tempArray[4];
		var currentFreeCredit = tempArray[5];
		document.varform.currentFreeViewCredit.value = currentFreeCredit; //Update the available credit on the page
		var currentCreditTotal = Number(currentCredit) + Number(currentFreeCredit);				
		requestNewLiceseExtend(true,currentCreditTotal,licSize,theLicDate,thePrevRef,isInvoiceCustomer);	
	}
}
//****************Define the actions when requesting a licence extention (Store the licence or prompt to add credit) 
function requestNewLiceseExtend(requestIt,currentCredit,licSize,theLicDate,thePrevRef,isInvoiceCustomer){
	if(requestIt){
		hideDialog();
		if((Number(currentCredit) < Number(mmLicencePriceExtend)) && (document.varform.isRetailOutlet.value != "yes")){   
			//Not enough credit, prompt to add credit or invoice for
			//Define if the full charge is to be invoiced or balance fro existing credits			
			var theAmountToInvoice = (Number(mmLicencePriceExtend) - Number(currentCredit));
			if(Number(theAmountToInvoice) == Number(mmLicencePriceExtend)){
				var invoiceType = "invoice";
			}else{
				var invoiceType = "partinvoice";
			}
			var outputHTML = "<h3>Licensing Info</h3><br/>";
			outputHTML += "<p class='error'><strong>Insufficient view credits found.</strong></p>";	
			if(isInvoiceCustomer == "yes"){
				outputHTML += "<form name='creditform' id='creditform' action='' method='post'><table cellspacing='3' cellpadding='0'><tr><td><p>Accept &pound;" + formatPrice(Math.round(theAmountToInvoice*100)/100) + " + VAT for this order</p></td><td><strong><a href='javascript:invoiceExtendLiceseArea(\"" + thePrevRef + "\",\"" + theLicDate + "\",\"" + licSize + "\",\"" + invoiceType + "\");'>Add to invoice</a></strong></td></tr>"; 
				if(document.varform.islitesite.value != "yes"){
					outputHTML += "<tr><td style='padding-top:5px;'><p>Pre-pay for credit by card (min. &pound;5)   &pound;<input name='addcredit' id='addcredit' type='text' size='3' value='5'></p></td><td style='padding-top:5px;'><strong><a href='javascript:addViewCredit(\"creditform\");'>Add Credit </a></strong></td></tr>";			
				}
				outputHTML += "</table></form>";
			}else{
				if(document.varform.islitesite.value != "yes"){
					outputHTML += "<form name='creditform' id='creditform' action='' method='post'><p>Pre-pay for credit by card (min. &pound;5)   &pound;<input name='addcredit' id='addcredit' type='text' size='3' value='5'>&nbsp;&nbsp;&nbsp;<strong><a href='javascript:addViewCredit(\"creditform\");'>Add Credit </a></strong></p></form>";
				}else{
					outputHTML += "<p class='error'><em>Adding credit not available</em></p>";
				}
			}	
			outputHTML += "<div style='position:absolute;top:5px;right:10px;'><a href='javascript:cancelDetailedPrompt();'>Close [x]</a></div>";						
			document.getElementById("previewsInfoContent").innerHTML = outputHTML;
			document.getElementById("previewsInfoContent").style.display = "block";
			callCufon();
		}else{
			//Store the licensed area			
			var thePayAction = "credit";
			var qstring = "prevref=" + thePrevRef + "&cid=" + document.varform.cid.value + "&centrex=" + map.getCenter().lon + "&centrey=" +  map.getCenter().lat + "&vxtent=" + map.getExtent().toBBOX() + "&lictype=extend&passeddate=" + theLicDate + "&payaction=" + thePayAction + "&compid=" + document.varform.companyid.value + "&licsize=" + licSize + "&isretailoutlet=" + document.varform.isRetailOutlet.value;		
			storePreviewReq = new ajaxObject('storeMMPreview.php', handleStorePreviewResponse);
			storePreviewReq.update(qstring,'POST');
		}						
	}else{
		hideDialog();
	}
}
//****************Draw the MasterMap licensed area to the map
function drawLicenseExtent(passedCoordinates,prevID,prevName,prevDate,theType){
	//Define the geometry of the area
	var pointList = [];			
	var theCoordArray = passedCoordinates.split(",");		
	for (c=0; c< theCoordArray.length ;c++){
		var theXY = theCoordArray[c].split(" ");
		var newPoint = new OpenLayers.Geometry.Point(theXY[0],theXY[1]);
		pointList.push(newPoint);
	}					
	var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
	var theLicensedFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing]),null);
	//Add id, name and expiry date as attributes of the extent
	theLicensedFeature.attributes.id = prevID;
	theLicensedFeature.attributes.name = prevName;
	theLicensedFeature.attributes.exdate = prevDate;
	//Add feature to the layer
	if(theType == "OSMM"){
		if(document.varform.isRetailOutlet.value == "yes"){
			invisibleStyle = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
			invisibleStyle.strokeColor = "none";
			invisibleStyle.strokeWidth = "0";
			invisibleStyle.fillOpacity = "0";					
			licensedLayer.style = invisibleStyle;		  
			licensedLayer.redraw();
		}	
		licensedLayer.addFeatures(theLicensedFeature);
	}else{
		licensed10kLayer.addFeatures(theLicensedFeature);
	}		
}
//****************Check if we have moved into a licenced area
function checkInLicensedArea(){
	//Firstly define if the area is urban-rural-moorland
	addURMcoverage();
}
//****************Defines if current view in licensed area and show user appropriate options
function performLicenceCheck(){
	//Define the licence size for new and licence extensions
	var licSize = getLicenceSize();	
	if(licensedLayer.features.length == 0){									//No licensed areas - prompt to add
		var creditAvailable = Number(document.varform.currentViewCredit.value) + Number(document.varform.currentFreeViewCredit.value);	//Credit available
		creditAvailable = formatPrice(Math.round(creditAvailable*100)/100);		//Format price correctly		
		if(Number(creditAvailable) < Number(mmLicencePrice)){
			var creditColour = "#ff0000";
		}else{
			var creditColour = "#33cc33";
		}
		//Show the licensing info
		var newExpireDate = getPreviewExpireyDate(new Date(),"new");						//Get expiry date			
		if(document.varform.isRetailOutlet.value == "yes"){
			createNewLiceseArea(licSize);
		}else{			
			var outputHTML = "<table cellspacing='2' cellpadding='5'>";	
			outputHTML += "<tr><td colspan='5'><h3>Switch to detail view?</h3><p style='font-size:13px;color:" + creditColour + ";'>(Existing credit available: <strong>&pound;" + creditAvailable + "</strong> + VAT)</p></td></tr>";
			outputHTML += "<tr><td colspan='5'>&nbsp;</td></tr>";
			outputHTML += "<tr style='background-color:#CCCCCC'><td width='170px'><p style='padding-left:5px;padding-right:5px;'><strong>Create New</strong><br/>(" + licSize + "m radius)</p></td><td width='120px'><p style='padding-left:5px;padding-right:5px;'><input name='mmpreviewref' id='mmpreviewref' value='Add a reference' size='14' onfocus='this.value=\"\"'></p></td><td width='80px'><p style='padding-left:5px;padding-right:5px;'>valid until " + newExpireDate + "</p></td><td width='20px'><p style='padding-left:5px;padding-right:5px;'>&pound;" + mmLicencePrice + "</p></td><td width='20px'><p style='padding-left:5px;padding-right:5px;'><input type='button' value='Go' name='gobuttonExtendNew' id='gobuttonExtendNew' onclick='createNewLiceseArea(\"" + licSize + "\");' /></p></td></tr>";	
			outputHTML += "<tr><td colspan='5'><br/><img src='images/whyOpt1.png' alt='Why opt for detailed mapping?' /></td></tr>"; 	
			outputHTML += "</table>";
			outputHTML += "<div style='position:absolute;top:5px;right:10px;'><a href='javascript:cancelDetailedPrompt();'>Close [x]</a></div>";		
			document.getElementById("previewsInfoContent").innerHTML = outputHTML
			document.getElementById("previewsInfoContent").style.display = "block";	
			callCufon();
		}
	}else{
		//Get map centre
		var mapCentrePoint = map.getCenter();
		//Get the map extent
		var viewExtent = map.getExtent().toBBOX();		
		//Create geometry of centre and extent to check intersections with the licensed areas
		var theExtentArray = viewExtent.split(",");	
		var pointList = [];
		var newPoint = new OpenLayers.Geometry.Point(theExtentArray[0],theExtentArray[1]);
		pointList.push(newPoint);
		var newPoint = new OpenLayers.Geometry.Point(theExtentArray[0],theExtentArray[3]);
		pointList.push(newPoint);
		var newPoint = new OpenLayers.Geometry.Point(theExtentArray[2],theExtentArray[3]);
		pointList.push(newPoint);
		var newPoint = new OpenLayers.Geometry.Point(theExtentArray[2],theExtentArray[1]);
		pointList.push(newPoint);
		var newPoint = new OpenLayers.Geometry.Point(theExtentArray[0],theExtentArray[1]);
		pointList.push(newPoint);					
		var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
		var theViewExtentGeom = new OpenLayers.Geometry.Polygon([linearRing]);	
		var theViewCentreGeom = new OpenLayers.Geometry.Point(mapCentrePoint.lon,mapCentrePoint.lat);
		//Loop thru all the licensed area to check if map centre intersects
		for(p=0; p < licensedLayer.features.length;p++){
			var centreIntersection = licensedLayer.features[p].geometry.intersects(theViewCentreGeom);
			if(centreIntersection){														//***Centre intersects licensed area - show MasterMap 
				if(mmLayer.getVisibility() == false){									//If MasterMap not showing 
					showLicensedArea();
				}
				break;
			}
		}	
		//Loop thru all the licensed area to check if view extent intersects
		if(centreIntersection == false){		
			if((mmLayer.getVisibility()) && (document.varform.isRetailOutlet.value != "yes")){ 		//Ensure Mastermap not showing
				toggleMapLayers("gb");	
			}
			for(p=0; p < licensedLayer.features.length;p++){
				var extIntersection = licensedLayer.features[p].geometry.intersects(theViewExtentGeom);
				if(extIntersection){
					var creditAvailable = String(Number(document.varform.currentViewCredit.value) + Number(document.varform.currentFreeViewCredit.value));	//Credit available
					creditAvailable = formatPrice(Math.round(creditAvailable*100)/100);		//Format price correctly
					if(Number(creditAvailable) < Number(mmLicencePrice)){
						var creditColour = "#ff0000";
					}else{
						var creditColour = "#33cc33";
					}
					//Show the licensing info													//***Centre outside licensed area but view extent overlaps - offer extension of licensed area							
					var newExpireDate = getPreviewExpireyDate(new Date(),"new");					//Get expiry date
					var existingExpireDate = getPreviewExpireyDate(licensedLayer.features[p].attributes.exdate,"existing");
					if(document.varform.isRetailOutlet.value == "yes"){
						extendArea(licensedLayer.features[p].attributes.exdate,licensedLayer.features[p].attributes.name,licSize);
					}else{
						var outputHTML = "<table cellspacing='2' cellpadding='5'>";
						outputHTML += "<tr><td colspan='5'><h3>Switch to detail view?</h3><p style='font-size:13px;color:" + creditColour + ";'>(Existing credit available: <strong>&pound;" + creditAvailable + "</strong> + VAT)</p></td></tr>";
						outputHTML += "<tr><td colspan='5'>&nbsp;</td></tr>";
						outputHTML += "<tr style='background-color:#CCCCCC'><td width='170px'><p style='padding-left:5px;padding-right:5px;'><strong>Create New</strong><br/>(" + licSize + "m radius)</p></td><td width='120px'><p style='padding-left:5px;padding-right:5px;'><input name='mmpreviewref' id='mmpreviewref' value='Add a reference' size='14' onfocus='this.value=\"\"'></p></td><td width='80px'><p style='padding-left:5px;padding-right:5px;'>valid until " + newExpireDate + "</p></td><td width='20px'><p style='padding-left:5px;padding-right:5px;'>&pound;" + mmLicencePrice + "</p></td><td width='20px'><p style='padding-left:5px;padding-right:5px;'><input type='button' value='Go' name='gobuttonExtendNew' id='gobuttonExtendNew' onclick='createNewLiceseArea(\"" + licSize + "\");' /></p></td></tr>";
						outputHTML += "<tr style='background-color:#CCCCCC'><td width='170px'><p style='padding-left:5px;padding-right:5px;'><strong>Extend Existing</strong<br/>(" + licSize + "m radius)</p></td><td width='120px'><p style='padding-left:5px;padding-right:5px;'>" + licensedLayer.features[p].attributes.name + ": <input name='mmpreviewrefsuffix' id='mmpreviewrefsuffix' value='Add a reference' size='14' onfocus='this.value=\"\"'></p></td><td width='80px'><p style='padding-left:5px;padding-right:5px;'>valid until " + existingExpireDate + "</p></td><td width='20px'><p style='padding-left:5px;padding-right:5px;'>&pound;" + mmLicencePriceExtend + "</p></td><td width='20px'><p style='padding-left:5px;padding-right:5px;'><input type='button' value='Go' name='gobuttonExtendNew' id='gobuttonExtendNew' onclick='extendArea(\"" + licensedLayer.features[p].attributes.exdate + "\",\"" + licensedLayer.features[p].attributes.name + "\",\"" + licSize + "\");' /></p></td></tr>";
						outputHTML += "<tr><td colspan='5'><br/><img src='images/whyOpt1.png' alt='Why opt for detailed mapping?' /></td></tr>"; 
						outputHTML += "</table>";
						outputHTML += "<div style='position:absolute;top:5px;right:10px;'><a href='javascript:cancelDetailedPrompt();'>Close [x]</a></div>";										
						document.getElementById("previewsInfoContent").innerHTML = outputHTML
						document.getElementById("previewsInfoContent").style.display = "block";
						callCufon();
					}
					break;
				}	
			}
		}	
		if(extIntersection == false){												//***View extent does not intersect licensed area - offer to license a new area			
			if(mmLayer.getVisibility()){											//Ensure Mastermap not showing
				toggleMapLayers("aerial");
			}
			var creditAvailable = String(Number(document.varform.currentViewCredit.value) + Number(document.varform.currentFreeViewCredit.value));	//Credit available			
			creditAvailable = formatPrice(Math.round(creditAvailable*100)/100);		//Format price correctly
			if(Number(creditAvailable) < Number(mmLicencePrice)){
				var creditColour = "#ff0000";
			}else{
				var creditColour = "#33cc33";
			}
			//Show the licensing info
			var newExpireDate = getPreviewExpireyDate(new Date(),"new");					//Get expiry date
			if(document.varform.isRetailOutlet.value == "yes"){
				createNewLiceseArea(licSize);
			}else{
				var outputHTML = "<table cellspacing='2px' cellpadding='5px'>";
				outputHTML += "<tr><td colspan='5'><h3>Switch to detail view?</h3><p style='font-size:13px;color:" + creditColour + ";'>(Existing credit available: <strong>&pound;" + creditAvailable + "</strong> + VAT)</p></td></tr>";
				outputHTML += "<tr><td colspan='5'>&nbsp;</td></tr>";
				outputHTML += "<tr style='background-color:#CCCCCC;'><td width='170px'><p style='padding-left:5px;padding-right:5px;'><strong>Create New</strong><br/>(" + licSize + "m radius)</p></td><td width='120px'><p style='padding-left:5px;padding-right:5px;'><input name='mmpreviewref' id='mmpreviewref' value='Add a reference' size='14' onfocus='this.value=\"\"'></p></td><td width='80px'><p style='padding-left:5px;padding-right:5px;'>valid until " + newExpireDate + "</p></td><td width='20px'><p style='padding-left:5px;padding-right:5px;'>&pound;" + mmLicencePrice + "</p></td><td width='20px'><p style='padding-left:5px;padding-right:5px;'><input type='button' value='Go' name='gobuttonExtendNew' id='gobuttonExtendNew' onclick='createNewLiceseArea(\"" + licSize + "\");' /></p></td></tr>";
				outputHTML += "<tr><td colspan='5'><br/><img src='images/whyOpt1.png' alt='Why opt for detailed mapping?' /></td></tr>"; 
				outputHTML += "</table>";
				outputHTML += "<div style='position:absolute;top:5px;right:10px;'><a href='javascript:cancelDetailedPrompt();'>Close [x]</a></div>";		
				document.getElementById("previewsInfoContent").innerHTML = outputHTML
				document.getElementById("previewsInfoContent").style.display = "block";
				callCufon();
			}
		}
	}	
}
//****************Get the date when the licensed area for the passed date will expire (in 12 months time)
function getPreviewExpireyDate(theDate,theType){	
	if(theType == "new"){										//New request = today's date
		var theYear = theDate.getFullYear();
		var theMonth = theDate.getMonth()+1;  //(jan == 0)
		var theDay = theDate.getDate();  
	}else if(theType == "existing"){							//Date when the request was made for a stored extent
		var dateArray = theDate.split("-");
		var theYear = Number(dateArray[0]);
		var theMonth = Number(dateArray[1]);
		var theDay = Number(dateArray[2]); 
	}	
	//Code for in 6 months time 
	var newMonth = theMonth + 6; 
	//Adjust if necessary
	if(newMonth > 12){
		newMonth = newMonth - 12;
		theYear = theYear + 1;
	}			
	if(((newMonth == 4) || (newMonth == 6) || (newMonth == 9) || (newMonth == 11)) && (theDay == 31)){
		theDay = 30;
	}else if((newMonth == 2) && (theDay > 28)){
		theDay = 28;
	}	
	//Ensure formatted correctly
	if(newMonth < 10){
		newMonth = "0" + String(newMonth);
	}
	if(theDay < 10){
		theDay = "0" + String(theDay);
	}
	var newExpireDate = String(theDay) + "-" + String(newMonth) + "-" + String(theYear);		
	//Return the date as a string
	return newExpireDate;
}
//****************Adds Urban-Rural-Moorland coverage to the view
function addURMcoverage(){														
	URMLayer.destroyFeatures();												//Delete features from the layer first
	var qstring = "vxtent=" + map.getExtent().toBBOX();		
	if(getURMReq != null){
		getURMReq.abort();
	}	
	getURMReq = new ajaxObject('getURM.php', handleURMResponse);
	getURMReq.update(qstring,'POST');	
}
//****************Handles the response from getting URM extents
function handleURMResponse(responseText, responseStatus){
	if(responseStatus == 200){
		if(responseText != ""){
			responseText = trim(responseText);
			var tempArray = responseText.split("_");			
			URMLayer.destroyFeatures();   //Destroy current extents added to the view									
			//Draw the extents				
			if(tempArray[1] != ""){
				var theURMArray1 = tempArray[0].split('|');
				var theURMArray2 = tempArray[1].split('|');			
				for(c=0; c < theURMArray1.length;c++){
					var pointList = [];			
					var theCoordArray = theURMArray1[c].split(",");		
					for (c1=0; c1 < theCoordArray.length;c1++){
						var theXY = theCoordArray[c1].split(" ");
						var newPoint = new OpenLayers.Geometry.Point(theXY[0],theXY[1]);
						pointList.push(newPoint);
					}					
					var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
					var URMExtentFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing]),null);	
					URMExtentFeature.attributes.id = theURMArray2[c];    //Apply attribute for Urban-Rural-Moorland
					URMLayer.addFeatures(URMExtentFeature);
				}
			}
			//Define if in a licensed area
			if(checkLicenceAfterGetURM){			//Call license check
				performLicenceCheck();
			}else{			//Don't call license check (this is necessary for the licence check when trying to zoom to a data extent) performLicenceCheckPreAutoZoom is called instead
				checkLicenceAfterGetURM = true;
				if(performLicenceCheckPreAutoZoom(boundsForLicenceCheckPreAutoZoom)){
					map.zoomToExtent(boundsForLicenceCheckPreAutoZoom);
				}
			}
			//Check if GM royalty needs recording
			recordGMView();
		}
	}
}
//****************Defines the licence size based on if Urban-Rural-Moorland
function getLicenceSize(){
	var theLicSize = "686";
	if(URMLayer.features.length > 0){				//If no features assumed to be Rural (686)
		var theViewCentreGeom = new OpenLayers.Geometry.Point(map.getCenter().lon, map.getCenter().lat);				//Get the view centre as a geometry
		//Loop thru all the features in the URBAN-RURAL-MOORLAND layer (only actually stores moorland and urban areas so all space is assumed to be rural
		var intersectionArea = "";
		for(p=0; p < URMLayer.features.length;p++){
			var centreIntersection = URMLayer.features[p].geometry.intersects(theViewCentreGeom);
			if(centreIntersection){														//***Centre intersects an urban or moorland extent 
				intersectionArea = URMLayer.features[p].attributes.id;
				break;
			}
		}
		//Define the licence size
		if(intersectionArea == "moorland"){
			theLicSize = "2747";
		}else if(intersectionArea == "urban"){
			theLicSize = "343";
		}
	}
	return theLicSize;
}
//****************Defines if current view in licensed area - allow user to zoom to MasterMap detail or not
function performLicenceCheckPreAutoZoom(passedBounds){
	if(document.varform.isRetailOutlet.value == "yes"){			//If retail outlet can zoom right in							
		var canZoomToIt = true;
	}else{														//Check if falls in a licenced area before we can zoom to it
		var canZoomToIt = false;
		//Define the licence size for new and licence extensions
		var licSize = getLicenceSize();	
		if(licensedLayer.features.length != 0){									//Has licensed areas				
			//Get map centre
			var mapCentrePoint = map.getCenter();
			///Get the  intended map extent
			var viewExtent = passedBounds.toBBOX();		
			//Create geometry of centre and extent to check intersections with the licensed areas
			var theExtentArray = viewExtent.split(",");	
			var pointList = [];
			var newPoint = new OpenLayers.Geometry.Point(theExtentArray[0],theExtentArray[1]);
			pointList.push(newPoint);
			var newPoint = new OpenLayers.Geometry.Point(theExtentArray[0],theExtentArray[3]);
			pointList.push(newPoint);
			var newPoint = new OpenLayers.Geometry.Point(theExtentArray[2],theExtentArray[3]);
			pointList.push(newPoint);
			var newPoint = new OpenLayers.Geometry.Point(theExtentArray[2],theExtentArray[1]);
			pointList.push(newPoint);
			var newPoint = new OpenLayers.Geometry.Point(theExtentArray[0],theExtentArray[1]);
			pointList.push(newPoint);					
			var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
			var theViewExtentGeom = new OpenLayers.Geometry.Polygon([linearRing]);	
			var theViewCentreGeom = new OpenLayers.Geometry.Point(mapCentrePoint.lon,mapCentrePoint.lat);		
			//Loop thru all the licensed area to check if map centre intersects
			for(p=0; p < licensedLayer.features.length;p++){
				var centreIntersection = licensedLayer.features[p].geometry.intersects(theViewCentreGeom);
				if(centreIntersection){														//***Centre intersects licensed area - show MasterMap 
					canZoomToIt = true;
					break;
				}
			}
		}
	}	
	return canZoomToIt;
}

//-------------------------------------------------------------------------OS ROYALTY SCRIPTS (UPDATE MAP CLICK AND DRAW COUNTERS)

//****************Defines the base map data currently displaying
function getMapBaseData(){
	var theBaseData = "";
	var selectedMapLayer = "";
	for (var i=0; i < document.maplayersform.optBaseLayers.length; i++){
		if(document.maplayersform.optBaseLayers[i].checked){	
			selectedMapLayer = document.maplayersform.optBaseLayers[i].value;
			break;
		}
	}
	if(selectedMapLayer == "aerial"){
		theBaseData = "GetMapping";
	}else if(selectedMapLayer == "hybrid"){
		theBaseData = "OS MasterMap";	
	}else{
		var currentMapScale = map.getScale();
		for(s=0;s < mapScales.length;s++){
			if(currentMapScale > mapScales[s]){
				theBaseData = baseMappingData[s-1];
				break;
			}
		}
		if(theBaseData == ""){
			theBaseData = baseMappingData[baseMappingData.length-1];
		}
		//If the user is a 10K viewer swap from Streetview
		if((theBaseData == "OS StreetView") && (document.varform.tenkMapType.value == "os10k")){
			theBaseData = "OS 10K";
		}
	}
	return theBaseData;
}
//****************Send request for updating the map click counter
function sndClickCntReq(){
	var theBaseData = getMapBaseData();			//Get the currently displayed base data
	if((document.varform.isRetailOutlet.value == "yes") && ((theBaseData == "OS 50K") || (theBaseData == "OS 25K"))){
		//No need to record
	}else{	
		var qstring = "maptype=" + theBaseData + "&centrex=" + map.getCenter().lon + "&centrey=" + map.getCenter().lat + "&vxtent=" + map.getExtent().toBBOX() + "&site=" + document.varform.thesite.value;			
		clickCountReq = new ajaxObject('mapclick_inc.php', handleClickCntResponse);
		clickCountReq.update(qstring,'POST');
	}
}
//****************Handles the response from updating the map click counter (Do nothing)
function handleClickCntResponse(responseText, responseStatus){
	if(responseStatus == 200){		 
		//No need to do anything
	}
}
//****************Handles the response from updating the map click counter (MasterMap value reduced when canceling a detialed request)
function handleClickCntResponse2(responseText, responseStatus){
	if(responseStatus == 200){		 
		map.zoomTo(11);				//Zoom out
	}
}
//****************Send request for updating the map draw counter
function sndDrawCntReq() {
	if((map.getScale() <= clickCountScale) && (document.varform.region.value == "gb")){			//Only record if GB below scale tolerance	
		var theBaseData = getMapBaseData();				//Get the currently displayed base data
		var qstring = "maptype=" + theBaseData + "&site=" + document.varform.thesite.value;	
		drawCountReq = new ajaxObject('mapdraw_inc.php', handleDrawCntResponse);
		drawCountReq.update(qstring,'POST');
	}
}
//****************Handles the response from updating the map draw counter (Do nothing)
function handleDrawCntResponse(responseText, responseStatus){
	if(responseStatus == 200){		 
		//No need to do anything
	}
}

//-------------------------------------------------------------------------OS 10K LICENSING SCRIPTS
//****************Send request for all licensed areas
function getOS10kLicensedAreas() {
	var qstring = "&cid=" + document.varform.cid.value + "&companyid=" + document.varform.companyid.value;	
	if(get10kPreviewsReq != null){
		get10kPreviewsReq.abort();
	}
	get10kPreviewsReq = new ajaxObject('getOS10kLicensedAreas.php', handleGetOS10kLicensedAreasResponse);
	get10kPreviewsReq.update(qstring,'POST');
}
//****************Handles the response from getting all licensed areas
function handleGetOS10kLicensedAreasResponse(responseText, responseStatus){
	if(responseStatus == 200){		
		if(responseText != ""){																//Check data returned
			if(responseText.indexOf('_' != -1)) {
				var thePreviewInfo = responseText.split('_');
				var numberFound = thePreviewInfo[0];
				var prevExtents = thePreviewInfo[1].split('|');
				var prevIDS = thePreviewInfo[2].split('|');
				var prevNames = thePreviewInfo[3].split('|');
				var prevDates = thePreviewInfo[4].split('|');				
				var newExpireDate = getPreviewExpireyDate(new Date(),"new");					//Get expiry date
				//Flag we have performed the initial license check
				document.varform.os10kViewExtents.value = numberFound;						
				//Draw extents to the map (invisible)
				if(Number(numberFound) > 0){
					for(n=0;n<Number(numberFound);n++){										
						var geomString = prevExtents[n].substring(9,(prevExtents[n].length-2));
						drawLicenseExtent(geomString,prevIDS[n],prevNames[n],prevDates[n],"OS10K");  
					}
				}
				//Check if in licenced area				
				performOS10kLicenceCheck()						
			}
		}		
	}
}
//****************Defines if current view in licensed area and show user appropriate options
function performOS10kLicenceCheck(){
	if(document.varform.isRetailOutlet.value == "yes"){							//If a retail outlet no need to prompt to show the MasterMap detail
		//showLicensedArea();
	}else{
		if(licensed10kLayer.features.length == 0){									//No licensed areas
			//Add new licence
			createNew10kLiceseArea();
		}else{
			//Get map centre
			var mapCentrePoint = map.getCenter();
			//Get the map extent
			var viewExtent = map.getExtent().toBBOX();		
			//Create geometry of centre and extent to check intersections with the licensed areas
			var theExtentArray = viewExtent.split(",");	
			var pointList = [];
			var newPoint = new OpenLayers.Geometry.Point(theExtentArray[0],theExtentArray[1]);
			pointList.push(newPoint);
			var newPoint = new OpenLayers.Geometry.Point(theExtentArray[0],theExtentArray[3]);
			pointList.push(newPoint);
			var newPoint = new OpenLayers.Geometry.Point(theExtentArray[2],theExtentArray[3]);
			pointList.push(newPoint);
			var newPoint = new OpenLayers.Geometry.Point(theExtentArray[2],theExtentArray[1]);
			pointList.push(newPoint);
			var newPoint = new OpenLayers.Geometry.Point(theExtentArray[0],theExtentArray[1]);
			pointList.push(newPoint);					
			var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
			var theViewExtentGeom = new OpenLayers.Geometry.Polygon([linearRing]);	
			var theViewCentreGeom = new OpenLayers.Geometry.Point(mapCentrePoint.lon,mapCentrePoint.lat);
			//Loop thru all the licensed area to check if map centre intersects
			for(p=0; p < licensed10kLayer.features.length;p++){
				var centreIntersection = licensed10kLayer.features[p].geometry.intersects(theViewCentreGeom);
				if(centreIntersection){														//***Centre intersects licensed area  - extend the current licence
					//Do nothing
					break;
				}
			}	
			//Loop thru all the licensed area to check if view extent intersects
			if(centreIntersection == false){
				for(p=0; p < licensed10kLayer.features.length;p++){
					var extIntersection = licensed10kLayer.features[p].geometry.intersects(theViewExtentGeom);
					if(extIntersection){
						//Extend licence
						extend10kArea(licensed10kLayer.features[p].attributes.exdate,licensed10kLayer.features[p].attributes.name);
						break;
					}
				}
			}	
			if(extIntersection == false){												//***View extent does not intersect licensed area - create a new licence			
				//Add new licence
				createNew10kLiceseArea();
			}
		}
	}	
}
//****************Add new OS 10k license area
function createNew10kLiceseArea(){
	var thePrevRef = "10k licence";		
	var qstring = "prevref=" + thePrevRef + "&cid=" + document.varform.cid.value + "&centrex=" + map.getCenter().lon + "&centrey=" +  map.getCenter().lat + "&vxtent=" + map.getExtent().toBBOX() + "&lictype=new&passeddate=&compid=" + document.varform.companyid.value + "&licsize=" + the10kLicSize;		
	store10kPreviewReq = new ajaxObject('store10kPreview.php', handleStore10kPreviewResponse);
	store10kPreviewReq.update(qstring,'POST');			
}
//****************Extends an OS 10k license area
function extend10kArea(theLicDate,licName){	
	//Define name for the extension	
	if(licName.indexOf(": extension") == -1){
		var thePrevRef = licName + ": extension";
	}else{
		var thePrevRef = licName;
	}
	//Store the licensed area			
	var qstring = "prevref=" + thePrevRef + "&cid=" + document.varform.cid.value + "&centrex=" + map.getCenter().lon + "&centrey=" +  map.getCenter().lat + "&vxtent=" + map.getExtent().toBBOX() + "&lictype=extend&passeddate=" + theLicDate + "&compid=" + document.varform.companyid.value + "&licsize=" + the10kLicSize;		
	store10kPreviewReq = new ajaxObject('store10kPreview.php', handleStore10kPreviewResponse);
	store10kPreviewReq.update(qstring,'POST');
}
//****************Handles the response from adding/extending an OS 10k license area
function handleStore10kPreviewResponse(responseText, responseStatus){
	if(responseStatus == 200){		 		
		if(responseText != ""){
			responseText = trim(responseText);	
			var responseArray = responseText.split("|");
			if(responseArray[0] == "yes"){
				drawLicenseExtent(responseArray[1],responseArray[2],responseArray[3],responseArray[4],"OS10K");  			
			}		
		}
	}
}

//-------------------------------------------------------------------------GOOGLE STREETVIEW SCRIPTS

//****************Updates the marker position when the SV location is changed
function updateSVMarkerPos(newPos){
	newPos1 = String(newPos).substring(1, (String(newPos).length-1));
	var tempArray = newPos1.split(",");	
	//Convert to OSNG/Irish NG (using geotools)
	var latitude=parseFloat(Number(tempArray[0]));
	var longitude=parseFloat(Number(tempArray[1]));
	if(document.varform.region.value == "ni"){			//Adjustment need for NI
		latitude = latitude - 0.000135;
		longitude = longitude - 0.0003905;
	}	
	var wgs84 = new GT_WGS84();
	wgs84.setDegrees(latitude, longitude);
	if(document.varform.region.value == "ni"){
		var irish=wgs84.getIrish(true);	
		var newOSPos = new OpenLayers.LonLat(irish.eastings,irish.northings);
	}else{
		var osgb=wgs84.getOSGB();
		var newOSPos = new OpenLayers.LonLat(osgb.eastings,osgb.northings);	
	}
	SVLayer.features[0].move(newOSPos);	
}
//****************Update the SV marker rotation on the map when the SV directio is changed
function updateSVMarkerDirection(passedDirection){
	//var newDirection = passedDirection * -1;
	defSVStyle = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
	defSVStyle.externalGraphic = 'http://shop.centremapslive.co.uk/whitelabel/images/sv_icon.png';
	defSVStyle.pointRadius = 20;
	defSVStyle.rotation = Number(passedDirection);
	SVLayer.features[0].style = defSVStyle;
	SVLayer.redraw();
}
//****************Initialize the SV marker drawing
function initSV(theAction){
	if(theAction == "activate"){
		drawSVPointControl.activate();
	}else if(theAction == "deactivate"){
		if(theSVSate == "off"){						//Not in the middle of drawing so deactivate
			drawSVPointControl.deactivate();
		}
	}
}
//****************Indicates that the state for drawing the SV marker is "on"
function setSVState(){
	theSVSate = "on";
}
//****************Show/Hide the SV popup window
function showHideSV(){
	if(document.getElementById("panoVisControl").innerHTML.indexOf("hide</a>")!= -1){
		document.getElementById("panoContent").style.display = "none";
		document.getElementById("panoContainer").style.height = "20px";
		document.getElementById("panoVisControl").innerHTML = "<a href='javascript:showHideSV();' style='color:#FFFFFF;margin-top:1px;margin-bottom:1px;'>show</a>";
	}else{
		document.getElementById("panoContent").style.display = "block";
		document.getElementById("panoContainer").style.height = "417px";
		document.getElementById("panoVisControl").innerHTML = "<a href='javascript:showHideSV();' style='color:#FFFFFF;margin-top:1px;margin-bottom:1px;'>hide</a>";
	}
}
//****************Close the SV popup window and kill the SV
function closeSV(){
	document.getElementById("panoContent").style.display = "none";
	document.getElementById("panoContainer").style.display = "none";
	SVLayer.destroyFeatures();
	modifySVControl.deactivate();
}
//****************Get the inital street view when the SV marker is drawn on the map
function getStreetView(){		
	if(SVLayer.features.length > 0){
		drawSVPointControl.deactivate();
		if(selFeatureControl != null){	
			selFeatureControl.deactivate();
		}					
		//Get the x-y location of the point
		var theSVLocGeometry = String(SVLayer.features[0].geometry);	
		theSVLocGeometry = theSVLocGeometry.substring(6,(theSVLocGeometry.length-1));
		//Convert to lat-long (using geoTools)
		var tempCoordArray = theSVLocGeometry.split(" ");
		if(document.varform.region.value == "ni"){
			var irish = new GT_Irish();
			irish.setGridCoordinates(tempCoordArray[0],tempCoordArray[1]);
			var wgs84=irish.getWGS84(true);
			var theLatLon = new google.maps.LatLng((wgs84.latitude + 0.000135),(wgs84.longitude + 0.0003905));	//adjustment need for NI ??
		}else{	
			osgb=new GT_OSGB();
			osgb.setGridCoordinates(tempCoordArray[0],tempCoordArray[1]);
			wgs84 = osgb.getWGS84();
			var theLatLon = new google.maps.LatLng(wgs84.latitude,wgs84.longitude);		
		}	
		//var theLatLon = new google.maps.LatLng(wgs84.latitude,wgs84.longitude);
		//Ensure the window are to show panorama is visiable		
		document.getElementById("panoContent").style.display = "block";
		document.getElementById("panoContainer").style.display = "block";
		document.getElementById("panoVisControl").innerHTML = "<a href='javascript:showHideSV();' style='color:#FFFFFF;margin-top:1px;margin-bottom:1px;'>hide</a>";
		svService = new google.maps.StreetViewService();								
		svPanorama = new  google.maps.StreetViewPanorama(document.getElementById("panoContent"));			
		svService.getPanoramaByLocation(theLatLon, 50, processSVData);								
		google.maps.event.addListener(svPanorama , 'position_changed', function() {
			//var positionCell = document.getElementById('position_cell');
			//positionCell.innerHTML = svPanorama.getPosition();
			posToPass = svPanorama.getPosition();
			updateSVMarkerPos(posToPass);	
		});	
		google.maps.event.addListener(svPanorama , 'pov_changed', function() {
			//var headingCell = document.getElementById('heading_cell');
			//var pitchCell = document.getElementById('pitch_cell');
			//headingCell.innerHTML = svPanorama.getPov().heading;
			//pitchCell.innerHTML = svPanorama.getPov().pitch;
			updateSVMarkerDirection(svPanorama.getPov().heading);
		});
	}			
}
//****************Set the initial SV
function processSVData(data, status) {
	if (status == google.maps.StreetViewStatus.OK) {
		svPanorama.setPano(data.location.pano);
		svPanorama.setPov({
			heading: 0,
			pitch: 10,
			zoom: 1
		});
		svPanorama.setVisible(true); 	
	}else{
		//Hide panorama window
		document.getElementById("panoContent").style.display = "none";
		document.getElementById("panoContainer").style.display = "none"; 
		showDialog('Warning','Street View data could not be found at this location.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');	
	}
}
//-------------------------------------------------End of file.
