
// createmap.js

///////////////////////////////////////////////////////////////////////////////////////////////////////

// Function definitions
///////////////////////////////////////////////////////////////////////////////////////////////////////


function LabelControl() {  }
LabelControl.prototype = new GControl();

// these are the settings for the sidebar
LabelControl.prototype.initialize = function(googlemap) {
labelContainer = document.createElement("div");
labelContainer.style.overflow="auto";
labelContainer.style.backgroundColor = "#cacadd";
labelContainer.style.border = "1px solid blue";

labelContainer.style.width=side_bar_width;
labelContainer.style.paddingLeft=side_bar_padding_left;
labelContainer.style.height=side_bar_height;

map.getContainer().appendChild(labelContainer);
return labelContainer;
}

// === This function picks up the click and opens the corresponding info window ===
function myclick(i) {
	  GEvent.trigger(gmarkers[i], "click");
}



// functions that open the directions forms
function tohere(i) {
gmarkers[i].openInfoWindowHtml(to_htmls[i]);
}
function fromhere(i) {
gmarkers[i].openInfoWindowHtml(from_htmls[i]);
}



function createMarker(point,name,html) {
// this funtion used to plot the main Facility on the map
var marker = new GMarker(point,{icon:EACicon});
				// show latlng
				//html += "<br>LatLng=" + point;
				//document.writeln("MainName=" + name + " " + point + "<BR><br>");
				
///////////////////// DIRECTIONS code
        // The info window version with the "to here" form open
        to_htmls[i] = html + '<br><br>Directions: <b>To here<\/b> - <a href="javascript:fromhere(' + i + ')">From here<\/a>' +
           '<br><br><strong>Please type your Start address:</strong><form action="http://maps.google.com/maps" method="get" target="_blank">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
           '<INPUT value="Get Directions" TYPE="SUBMIT">' +
           '<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + 
                  // "(" + name + ")" + 
           '"/>';
        // The info window version with the "to here" form open
        from_htmls[i] = html + '<br><br>Directions: <a href="javascript:tohere(' + i + ')">To here<\/a> - <b>From here<\/b>' +
           '<br><br><strong>Please type your End address:</strong><form action="http://maps.google.com/maps" method="get"" target="_blank">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' +
           '<INPUT value="Get Directions" TYPE="SUBMIT">' +
           '<input type="hidden" name="saddr" value="' + point.lat() + ',' + point.lng() +
                  // "(" + name + ")" + 
           '"/>';
        // The inactive version of the direction info
        html = html + '<br><br>Directions: <a href="javascript:tohere('+i+')">To here<\/a> - <a href="javascript:fromhere('+i+')">From here<\/a>';
//////////////////////////////	
//	document.writeln("<br>" + "html=" + html + "<br>");			
				
GEvent.addListener(marker, "click", function() {

  marker.openInfoWindowHtml(html);
});

// save the info we need to use later for the side_bar
gmarkers[i] = marker;
i++;
return marker;
}

function createPolyMarker(point) {
var marker = new GMarker(point,{icon:EACicon});


// er...
GEvent.addListener(marker, "click", function() {

  marker.openInfoWindowHtml(html);
});
// save the info we need to use later for the side_bar
gmarkers[i] = marker;
i++;
// to here


return marker;
}



function createMarkerOthers(point,name,html,CentreType,ThisIconImagePath,ThisShadowPath,TypeCount,IWidth,IHeight,SWidth,SHeight,PopUpType) {
// this function is used to plot all the other points on the map

var EACicon = new GIcon();
EACicon.image = ThisIconImagePath;
var marker = new GMarker(point,{icon:EACicon});
///////////////////// DIRECTIONS code
        // The info window version with the "to here" form open
        to_htmls[i] = html + '<br><br>Directions: <b>To here<\/b> - <a href="javascript:fromhere(' + i + ')">From here<\/a>' +
           '<br><br><strong>Please type your Start address:</strong><form action="http://maps.google.com/maps" method="get" target="_blank">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
           '<INPUT value="Get Directions" TYPE="SUBMIT">' +
           '<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + 
                  // "(" + name + ")" + 
           '"/>';
        // The info window version with the "to here" form open
        from_htmls[i] = html + '<br><br>Directions: <a href="javascript:tohere(' + i + ')">To here<\/a> - <b>From here<\/b>' +
           '<br><br><strong>Please type your End address:</strong><form action="http://maps.google.com/maps" method="get"" target="_blank">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' +
           '<INPUT value="Get Directions" TYPE="SUBMIT">' +
           '<input type="hidden" name="saddr" value="' + point.lat() + ',' + point.lng() +
                  // "(" + name + ")" + 
           '"/>';
        // The inactive version of the direction info
        html = html + '<br><br>Directions: <a href="javascript:tohere('+i+')">To here<\/a> - <a href="javascript:fromhere('+i+')">From here<\/a>';
//////////////////////////////	
	
//document.writeln("<br>" + "html=" + html + "<br>");



EACicon.shadow = ThisShadowPath;
EACicon.shadowSize = new GSize(SWidth, SHeight);

// NOTE: WE NEED THE ICONSIZE SETTING TO MAKE IT WORK IN IE, BUT FIREFOX DOESN'T NEED THIS!!! ALSO true for shadows
if ((IWidth != 0) && (IHeight !=  0)){
	EACicon.iconSize = new GSize(IWidth, IHeight);
}
else {
	IWidth = 20;
	IHeight = 34;
	EACicon.iconSize = new GSize(IWidth, IHeight);
}


// set the Anchor point to be half the width and the full height. This is the middle of the bottom of the icon image.
var AnchorX = IWidth / 2;
EACicon.iconAnchor = new GPoint(AnchorX, IHeight);  // pixel point of the icon which will point to the item
EACicon.infoWindowAnchor = new GPoint(10, 11); // pixel point where the 'arrowpoint' of the popup box should sit		

				// show latlng
				// html += "<br>LatLng=" + point;
				//document.writeln("Name=" + name + " " + point + "<BR>");


// RH changed this for VEAMap to show info window on mouseover and remove on mouseout.
// It determines if the popup is activated on click or mouseover.
// This setting depends on CPArray[x][11] which determines PopUpType

if (PopUpType == "mouseover"){
	GEvent.addListener(marker, "mouseover", function() {
	// this is undocumented map.open.... method - remember if using this, use marker.getLatLng method:
	map.openInfoWindowHtml(marker.getLatLng(),html,{pixelOffset:PopOff});
	});
	GEvent.addListener(marker, "mouseout", function() {
	
	  marker.closeInfoWindow();
	});
}
else {
	GEvent.addListener(marker, "click", function() {

	marker.openInfoWindowHtml(html,{pixelOffset:PopOff});
	});
}


// save the info we need to use later for the side_bar
gmarkers[i] = marker;

i++;
return marker;
}




function CTypeSelected(CType) {
var Selected = 9999999;
for ( var ckey in CTypeArray ) {
	if (CTypeArray[ckey] == CType) {
		Selected = ckey;
	}
}
return Selected;
}




function AddOrRemoveLayer(CType) {
var CTypeString = "";
var Position = CTypeSelected(CType);
if (Position != 9999999) {
	// need to remove it from the string (i.e. unselect it)
	CTypeArray.splice(Position,1);
}
else {
	// need to add it to the string (i.e. select it)
	CTypeArray.unshift(CType);
}
CTypeString = CTypeArray.toString();
var GoHere = PageAddress + "?UIN=" + ThisUIN + "&XREF=" + MainEast + "&YREF=" + MainNorth + "&Town=" + FacTown + "&Width=" + MapWidth + "&Height=" + MapHeight + "&ShowOthers=" + ShowOtherThings + "&Ctype=" + CTypeString;
window.location = GoHere ;
return CTypeString;
}




// This function parses the FacArray of all Facilities in the town area:
function parseArray( strUniqueKey, aArrayToParse )
{
	if ( aArrayToParse == null )	{
		//document.writeln( strUniqueKey + ": Array is null" );
		return;
		}
	
	if ( aArrayToParse.length == undefined )	{
		//document.writeln( strUniqueKey + ": Parameter is not an array" );
		return;
		}
	var LastCentreType = "FIRST TIME ROUND THE LOOP";
	var TypeCount = 1;
	var bSomething = false;
	var PopType = "click";   // for Facilities, always make the popup activate on click.
	for ( var strKey in aArrayToParse )	{
		bSomething = true;
		var item = aArrayToParse[ strKey ];	
//			document.writeln( "<BR>" );
//			document.writeln( strUniqueKey + ": " + item );
			// GOT AN ITEM SO CREATE THE POINTS:
			east=aArrayToParse[strKey][2];
			north=aArrayToParse[strKey][3];
			geo = NEtoLL(east, north);
			lat = geo.latitude * rad2deg;
			lon = geo.longitude * rad2deg;
			var point = new GLatLng(lat ,lon);
			var FacName=aArrayToParse[strKey][1] + " ";
			var EACCentreType=aArrayToParse[strKey][4];
			var EACCTypeID = aArrayToParse[strKey][5];



// check the querystring CType to see if it is the queried content Type

			if (EACCentreType != LastCentreType) {
				LastCentreType = EACCentreType;				
				// find the icon for this Facility Type using the function:
				var ImagePathArray = new Array();
				ImagePathArray = setImagePath(EACCTypeID);
				IconImagePath = ImagePathArray[0];
				var ThisIconWidth = ImagePathArray[1];
				var ThisIconHeight = ImagePathArray[2];
				var ShadowPath = ImagePathArray[3];
				var ShadowWidth = ImagePathArray[4];
				var ShadowHeight = ImagePathArray[5];
				
				
				// if ImagePath holds the default blue icon, then it means no special icon for this FacType was found
				// so use the numbered red balloons, otherwise we must plot the special icon on the sidebar
				if (IconImagePath == "/images/icons/blue/blank.png") {
					// pick up the icon to display using the Typecount as an identifier:
					IconImagePath = "/images/icons/0_to_99_markers/markers/marker"+TypeCount+".png";
					// if the centretype is one of the ones selected in the querystring then increment the TypeCount:						
					if (CTypeSelected(EACCTypeID) != 9999999) {
						TypeCount++;
					}
				}
				
				
				// To view ALL of this type of Facility in East Ayrshire.....
				if (CTypeSelected(EACCTypeID) != 9999999) {	
					var start_bar_html = "";
					start_bar_html += "<img src='" + IconImagePath + "' width=15 align=left>" + " - ";
					start_bar_html +="<a href='#' style=cursor:pointer onClick=AddOrRemoveLayer('" + EACCTypeID + "')>" + EACCentreType + "</a>";						
					start_bar_html += "<a href=/comser/viewCentreType.asp?Ctype=" + EACCTypeID + " target=_parent> - (ALL)</a><br><br><br>";
					// included an extra <br> to acomodate the icon image
					side_bar_html = start_bar_html + side_bar_html;												
					
				}
				else {	
					// first time, put Further Options header into the sidebar:
					if ((Foptions == 0) && (CType1 != "") && (CType1 != null)) {
						var head_bar_html = "<hr><strong>Further options:</strong><br><br>";
						side_bar_html += head_bar_html;
						Foptions = 1; // i.e. done once
					}
					
					side_bar_html +="<li><a  href='#' style=cursor:pointer onClick=AddOrRemoveLayer('" + EACCTypeID + "')>" + EACCentreType + "</a>";						
					side_bar_html += "<a href=/comser/viewCentreType.asp?Ctype=" + EACCTypeID + " target=_parent> - (ALL)</a></li>";							
				};
	
			}
			if (CTypeSelected(EACCTypeID) != 9999999) {
			// only plot it if it is one of the centretypes selected in the querystring:
				// Build an html variable to hold the html for the popup box when the point is clicked.
				var FacHTML = "<div style='width:" + PopWidth+";height:" + PopHeight+";font-family:" + PopFontFamily+";font-size:" + PopFontSize+"'>";
				FacName+="<br>"; // +"("+FacTown+")";
				FacHTML += "<a href=/comser/viewrecord.asp?UIN=" + aArrayToParse[strKey][0]  + " target=_parent>click here for information on this Facility</a><br>";
				var ImageFile = "/CouncilFacilitiesImages/"+ aArrayToParse[strKey][0] + ".jpg";
				
				// DoesImageExist function will return True or False by the Image pre-fetch in the asp code at the top of the page
				var ImageExists = aArrayToParse[strKey][6];
				var side_bar_image_html = "";

				if (ImageExists)
				{
					// image exists so add it to the popup box html, else it will just miss it out:	
						FacHTML += "<img src="+ImageFile+">";
					// also add the image to the sidebar:
						side_bar_image_html = "<img src="+ImageFile+">";
				}
				FacHTML += "</div>";
				
				marker = createMarkerOthers(point,FacName,FacHTML,EACCentreType,IconImagePath,ShadowPath,TypeCount,ThisIconWidth,ThisIconHeight,ShadowWidth,ShadowHeight,PopType);
				map.addOverlay(marker);	
				            
            // ==== Each time a point is found, extent the bounds ato include it =====
            bounds.extend(point);
            	
			}	
			i++;
//			document.writeln( "<BR>" + IconImagePath);
		}  // end of for loop
	
	if ( !bSomething )	{
		document.writeln( "<BR>" + strUniqueKey + ": THERE HAS BEEN AN ERROR. PLEASE ADVISE WEBTEAM. FacArray is empty" );
		}
	
//	document.writeln( "<BR>*** " + strUniqueKey + ": done!<HR>" );
} // end of function parsearray



// array sorting function for 2-D arrays, with the element to sort on
function myObjectBubbleSort(arrayName,length,element) {
    for (var i=0; i<(length-1); i++) {
        for (var j=i+1; j<length; j++) {
            if (arrayName[j][element] < arrayName[i][element]) {
                var dummy = arrayName[i];
                arrayName[i] = arrayName[j];
                arrayName[j] = dummy;
            }
         }
    }
}

// array display function:
function showObjectArray(object,length,element) {
    var output = '';
    for (var i=0; i<length; i++) {
        for (var j=0; j<element; j++) {
            output += object[i][j] + ' ';
        }
    output += '<BR>';
    }
    document.write(output + '<BR>');
}


///////////////////////////////////////
// This function parses the CPArray of all Custom Points that have been added in <pagename>.js:
function parseCParray( strUniqueKey, aArrayToParse )
{
	if ( aArrayToParse == null )	{
		//document.writeln( strUniqueKey + ": Array is null" );
		return;
		}
	
	if ( aArrayToParse.length == undefined )	{
		//document.writeln( strUniqueKey + ": Parameter is not an array" );
		return;
		}
		
// SORT ARRAY:
myObjectBubbleSort(aArrayToParse, aArrayToParse.length, 4); // sort on CPType
// Display sorted array for testing:
// showObjectArray(aArrayToParse, aArrayToParse.length, 4);	
//		return 0;

	var LastCentreType = "FIRST TIME ROUND THE LOOP";
	var TypeCount = 1;
	var bSomething = false;
	for ( var strKey in aArrayToParse )	{
			bSomething = true;
			var item = aArrayToParse[ strKey ];	
			var CPUIN=aArrayToParse[strKey][0]
			var CPName=aArrayToParse[strKey][1] + " ";
			var CPType=aArrayToParse[strKey][4];
			var CPIconPath = aArrayToParse[strKey][5];
			var CPImagePath = aArrayToParse[strKey][6];
			var CPCoordType = aArrayToParse[strKey][7];
			var CPThisIconWidth = aArrayToParse[strKey][8];
			var CPThisIconHeight = aArrayToParse[strKey][9];
			var CPThisLink = aArrayToParse[strKey][10];
			var PopType = aArrayToParse[strKey][11];
			if (CPThisLink == "UIN") {
				CPThisLink = "/comser/viewrecord.asp?UIN=" + CPUIN
			}

			// GOT AN ITEM SO CREATE THE POINTS:
			east=aArrayToParse[strKey][2];
			north=aArrayToParse[strKey][3];
			// if coords come from nlpg then convert them to Google decimal coords
			// else, don't convert them
			if (CPCoordType == "NLPG") {
				geo = NEtoLL(east, north);
				lat = geo.latitude * rad2deg;
				lon = geo.longitude * rad2deg;
			}
			else {
				lat = east;
				lon = north;
			}
			
// create the map point with the calculated lat and lon:		
			var point = new GLatLng(lat ,lon);
		
			
//			document.writeln("CPName=" + CPName + "<br>" + "CPCoordType=" + CPCoordType + "<br>lat=" +lat + " lon=" + lon + "<br>");
// check the querystring CType to see if it is the queried content Type

			if (CPType != LastCentreType) {
				LastCentreType = CPType;				
				// find the icon for this Facility Type using the function:
				var ImagePathArray = new Array();
				//ImagePathArray = setImagePath(CPType);
				IconImagePath = CPIconPath;
				var ThisIconWidth = CPThisIconWidth;
				var ThisIconHeight = CPThisIconHeight;
				var ShadowPath = CPIconPath;
				var ShadowWidth = CPThisIconWidth;
				var ShadowHeight = CPThisIconHeight;
				
				
				// if IconImagePath holds the default blue icon, then it means no special icon for this FacType was found
				// so use the numbered red balloons, otherwise we must plot the special icon on the sidebar
				if (IconImagePath == "/images/icons/blue/blank.png") {
					// pick up the icon to display using the Typecount as an identifier:
					IconImagePath = "/images/icons/0_to_99_markers/markers/marker"+TypeCount+".png";
					//  increment the TypeCount:						

					TypeCount++;
				}
				
			


				// first time, put Further Options header into the sidebar:
				// but only if (ShowOtherThings != 1) because then it will have already happened for Facilities
				if (ShowOtherThings != 1) { 
					if ((Foptions == 0) && (CType1 != "") && (CType1 != null)) {
						var head_bar_html = "<hr><strong>Further options:</strong><br><br>";
						side_bar_html += head_bar_html;
						Foptions = 1; // i.e. done once
					}
				}
				
				// if there is an icon for this group of things or this thing then add it to the sidebar, else have <li>
				side_bar_image_html = "";
				if (IconImagePath != "") {
					// also add the icon image to the sidebar:
						side_bar_image_html = "<img src="+IconImagePath+" width=20>";
						side_bar_html +=side_bar_image_html + "<a href=" + CPThisLink + "&Ctype=" + CPType + ">" + CPType + "</a><br>";
				}
				else {
				side_bar_html +="<li><a href=" + CPThisLink + "&Ctype=" + CPType + ">" + CPType + "</a></li>";
				}
			}

				// Build an html variable to hold the html for the popup box when the point is clicked.
				var CPHTML = "<div style='width:"+PopWidth+";height:"+PopHeight+";font-family:"+PopFontFamily+";font-size:"+PopFontSize+"'>";
				CPHTML += CPName;
				if (CPThisLink !=""){
					CPHTML += "<br><a href=" + CPThisLink + ">click here for information on this Facility</a><br>";
					}
				var ImageFile = "/CouncilFacilitiesImages/"+ aArrayToParse[strKey][0] + ".jpg";
				
				// DoesImageExist function will return True or False by the Image pre-fetch in the asp code at the top of the page
//				var ImageExists = aArrayToParse[strKey][5];
				var side_bar_image_html = "";

				if (CPImagePath != "")
				{
					// image exists so add it to the popup box html, else it will just miss it out:	
						CPHTML += "<img src=" + CPImagePath + ">";
				}
				CPHTML+="</div>";

				marker = createMarkerOthers(point,CPName,CPHTML,CPType,IconImagePath,ShadowPath,TypeCount,ThisIconWidth,ThisIconHeight,ShadowWidth,ShadowHeight,PopType);
				map.addOverlay(marker);	
				            
            // ==== Each time a point is found, extent the bounds ato include it =====
            bounds.extend(point);	

			i++;
//			document.writeln( "<BR>" + IconImagePath);
		}  // end of for loop
		
	
	if ( !bSomething )	{
		document.writeln( "<BR>" + strUniqueKey + ": THERE HAS BEEN AN ERROR. PLEASE ADVISE WEBTEAM. CP Array is empty" );
		}
	
//	document.writeln( "<BR>*** " + strUniqueKey + ": done!<HR>" );
} // end of function parseCParray
/////////////// end of Parse Custom Points Array






// This function will draw a polygon of all the points in PolyArray:
function parsePolyArray( strUniqueKey, aArrayToParse )
{
	if ( aArrayToParse == null )	{
//		document.writeln( strUniqueKey + ": Array is null" );
		return;
		}
	
	if ( aArrayToParse.length == undefined )	{
//		document.writeln( strUniqueKey + ": Parameter is not an array" );
		return;
		}
	var bSomething = false;
	for ( var strKey in aArrayToParse )	{
		bSomething = true;
		var item = aArrayToParse[strKey];	
			east=aArrayToParse[strKey][0];
			north=aArrayToParse[strKey][1];
//	east=243947;  // HQ xref for testing
//	north=637468;  // HQ yref for testing
			geo = NEtoLL(east, north);
			lat = geo.latitude * rad2deg;
			lon = geo.longitude * rad2deg;
//	document.writeln(aArrayToParse[strKey]);
//	document.writeln( "lat=" + east + " (" + geo.latitude + ") and " + "lon=" + north + " (" + geo.longitude + ") <br>");
			var point = new GLatLng(lat ,lon);
				marker = createPolyMarker(point);



	
				
		}  // end of for loop
	
	if ( !bSomething )	{
		document.writeln( "<BR>" + strUniqueKey + ": THERE HAS BEEN AN ERROR. PLEASE ADVISE WEBTEAM. Poly Array is empty" );
		}
	
//	document.writeln( "<BR>*** ParsePolyArray " + strUniqueKey + ": done!<HR>" );
} // end of function parsePolyarray


///////////////////////////////////////////////////////////////////////////////////////////////////////
// end of Function definitions
///////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////












if (GBrowserIsCompatible()) {

var qs=new Querystring();	


var htmls = [];
var to_htmls = [];
var from_htmls = [];



// test if CoordType is overridden in the querystring. By default, CoordType should be set to '1' in [pagename].js
// so that the coordinate conversion is done, however you can change this in [pagename].js, or override in the querystring
var CoordType=qs.get("CoordType");
var ConversionReqd = 1; // default to yes, coordinates should be converted from eastings / northings (NLPG format)
if (CoordType != null) {
	if (CoordType == "LatLng") {
		// coordinates already in latitude / longitude format required by google.
		ConversionReqd = 0;
	}
}


// RH convert OS Eastings and Northings from Gazetteer to Latitude and Longitude needed by Google map: 
// east and north variables hold the gazetteer easting and northing values as retrieved from NLPG

if (ConversionReqd){
	var MainEast=east;
	var MainNorth=north;
	geo = NEtoLL(east, north);
//	document.writeln("geo=" + geo.latitude + "<br>");
	lat = geo.latitude * rad2deg;
	lon = geo.longitude * rad2deg;
}
else {
lat = east;
lon = north;
}

//  document.writeln("Conv Reqd=" + ConversionReqd + "<br>");
//  document.writeln("east=" + east + " and north=" + north + "<br>");
// document.writeln("geo.lat=" + geo.latitude + " and geo.lng=" + geo.longitude + "<br>");
//  document.writeln("lat=" + lat + " and lon=" + lon + "<br>");
// variables to hold latitude and longitude of the Facility being displayed
var FacLat = lat; // - 0.00005;  fudge factor
var FacLong = lon; // +.00135;   fudge factor
// variables to hold latitude and longitude of centre of map
//    var CentreLat = 55.606078;    // council hq for testing
//    var CentreLong = -4.479118;   // council hq for testing
// make the centre of the map be the Facility being displayed:
var CentreLat = FacLat;
var CentreLong = FacLong;


//	set CType1 and ThisUIN variables from the querystring
var CType1 = qs.get("Ctype");			
var ThisUIN = qs.get("UIN");
var CTypeArray = new Array();
if (CType1 != null) {	
//	set up an array of the CTypes found in the querystring

	CTypeArray = CType1.split(",");
	var NoofCTypes=CTypeArray.length;
	CTypeArray.sort;
}

var FacName="Your Location";
var FacTown=qs.get("Town");

LabelControl.prototype.getDefaultPosition = function() {
return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 33));
}



// if chosen NOT to show Other Facilities, the resize the sidebar:
var StillShowThings = qs.get("ShowOthers") || ShowOtherThings;

if (StillShowThings == 0) {
	side_bar_height = SmallSidebarHeight;
	ShowOtherThings =0;
}
if (StillShowThings == 1) {
	side_bar_height = LargeSidebarHeight;
	ShowOtherThings =1;
}

//  create the marker and set up the event window etc
var gmarkers = [];
var i=0;
var side_bar_html = "";
var side_bar_image_html = "";

// === Create the map ===
var map = new GMap2(document.getElementById("map"));
// RH the Labelcontrol puts the sidebar with clickable labels onto the map

if (side_bar_reqd == 1) {
	map.addControl(new LabelControl());
}
if (map_control_reqd == 1) {
	map.addControl(new GMapTypeControl());
}
if (GLarge_Control == 1) {
	map.addControl(new GLargeMapControl());
}
if (GLarge_Control == 0) {
	map.addControl(new GSmallMapControl());
}
if (Show_Overview_Map == 1) {
	map.addControl(new GOverviewMapControl());
}

// set the Popup offset:
var PopOff = new GSize(PopXOffset, PopYOffset);



// set the MapWidth, MapHeight,  variables to store the current map dimensions:
		var Size = map.getSize();
		var MapWidth = qs.get("Width"); //Size.width; 
		var MapHeight = qs.get("Height"); //Size.height; 

//document.writeln("width="+ Size.width); //MapWidth);

// set up a point variable to hold the centre of the map
var centreofmap = new GLatLng(CentreLat,CentreLong); 



///////////////////////////////////////////////////////////////////////////////////////////
// set the map centre and zoom level.
// defaulted from from <pagename>.js, or use the querystring:
map.setCenter(centreofmap, MapZoomLevel);   
///////////////////////////////////////////////////////////////////////////////////////////


/////////////////////////////////////
// set the cursor, if variable cursorSetting is set in [pagename].js, else it will default to the hand.
// see: http://econym.googlepages.com/cursors.htm
// first, check if the variable has been defined at all (older [pagename].js scripts may not have this):
if (typeof cursorSetting != "undefined") {
	map.getDragObject().setDraggableCursor(cursorSetting);
}
else {
	map.getDragObject().setDraggableCursor("default");
}


// set an empty GLatLngBounds object in case we need to set the map bounds later on
var bounds = new GLatLngBounds();


// CUSTOM POINTS	
// parse the CPArray (as set up in <pagename>.js) to plot the Custom Points:
	if (ShowCustomPoints == 1){
		parseCParray("Root", CPArray);
	}

	var CPside_bar_html = "";
	if (ShowCustomPoints == 1) {
		// if we had Custom Points to show, add a <hr> to the sidebar:
		CPside_bar_html = side_bar_html + "<hr>";
		side_bar_html = "";
	}
	
var Facside_bar_html = "";

if (ShowOtherThings == 1) { 
	
	// First, plot the other local points using the other marker icon
	// Plot the other points first, so that the Facility we are displaying ends up on top!
	// use the FacArray created by the ASP code up top
	// this code sets up a new DEFAULT icon for the map in case one hasn't been set in <pagename>.js
	// - use the shieldiconbw as the default, but later in the code
	// in (create markers functions) we can select coloured icons depending on the Facility (centre) type
	var EACicon = new GIcon();
	var IconImagePath="http://www.east-ayrshire.gov.uk/images/icons/shieldiconbw.png";  // set it to the default b/w icon
	EACicon.image = IconImagePath;
	//EACicon.shadow = "http://www.east-ayrshire.gov.uk/images/icons/shieldiconbw.png";
	EACicon.iconSize = new GSize(21, 24);
	//EACicon.shadowSize = new GSize(41, 45);
	EACicon.iconAnchor = new GPoint(7, 22);  // pixel point of the icon which will point to the item
	EACicon.infoWindowAnchor = new GPoint(10, 11); // pixel point where the 'arrowpoint' of the popup box should sit
	
	
	var NewFacArray = new Array();
	NewFacArray=GetFacArray();       // NOTE: this function is defined in pagename.asp!!!! If it's not there, it will fail.
	var LenFacArray = NewFacArray.length;
//	document.writeln("NFA.length=" + NewFacArray.length);
	var Facside_bar_html = "";
	
	// TEST if there are any Facs in this locale:
	if (LenFacArray > 0){	
		if ((CType1 == "") || (CType1 == null)) {
			side_bar_html += "<strong>Options:</strong><br><br>";
		}
		var Foptions = 0;
		parseArray( "Root", NewFacArray );	
	//		document.writeln("len="+NewFacArray.length);
		Facside_bar_html = side_bar_html;
		side_bar_html = "";
	}
	else {
		Facside_bar_html = "Sorry, there aren't any Council facilities for your town in our database.<br>";
		// set the MapWidth, MapHeight, MapZoomLevel variables to store the current map dimensions:
		var Size = map.getSize();
		var MapWidth = Size.width; 
		var MapHeight = Size.height;
		var MapZoomLevel = map.getZoom(); 
		Facside_bar_html += "<br><a href=" + PageAddress + "?UIN=" + ThisUIN + "&XREF=" + MainEast + "&YREF=" + MainNorth + "&Town=" + FacTown + "&Width=" + MapWidth + "&Height=" + MapHeight + "&ZoomLevel=" + MapZoomLevel  + "&ShowOthers=0> HIDE</a><br><hr>";
//		Facside_bar_html += "now_width=" + MapWidth + ".<br>";
//		Facside_bar_html += "now_height=" + MapHeight + ".<br>";
//		Facside_bar_html += "now_zoomlevel=" + MapZoomLevel + ".<br>";
	}
}


// test if ShowPolygon has been set in <pagename>.js
if (ShowPolygon == 1){

	parsePolyArray( "Root", PolyArray );

}




var Mainside_bar_html = "";		
// Test if ShowAMainPoint has been set in the parameters:
if (ShowAMainPoint) {
		
	// NOW PLOT THE MAIN FACILITY 



//  MAIN POINT ICON SETTINGS
	// this code sets up a new icon for the main point - set the values in <pagename>.js
	// if no values set, then use defaults:
	if (MainPointIconPath == "") {
		MainPointIconPath = "/images/icons/shieldIcon.png";
		MainPointShadowPath = "/images/icons/shieldicon.png";
		MainPointSidebarIcon = MainPointShadowPath;
		MainPointIconWidth = 41;
		MainPointIconHeight = 45;
		MainPointShadowWidth = 41;
		MainPointShadowHeight = 45;
		MainPointIconXAnchor = 28; // this is the x coord of the pixel on the icon that sits on the map point (anchor)
		MainPointIconYAnchor = 40; // this is the y coord of the anchor point
		MainPointInfoXAnchor = 20; // this is the x coord of the popup info box anchor point (when you click the map icon)
		MainPointInfoYAnchor = 25; // this is the y coord of the popup info box anchor point (when you click the map icon)
	}
	var EACicon = new GIcon();
	EACicon.image = MainPointIconPath;
	//EACicon.shadow = MainPointShadowPath;
	var side_bar_icon = MainPointSidebarIcon;
	var side_bar_icon_html = "<img src=" + side_bar_icon + " align=left>";
	EACicon.iconSize = new GSize(MainPointIconWidth, MainPointIconHeight);
	EACicon.shadowSize = new GSize(MainPointShadowWidth,MainPointShadowHeight);
	EACicon.iconAnchor = new GPoint(MainPointIconXAnchor,MainPointIconYAnchor);  // pixel point of the icon which will point to the item
	EACicon.infoWindowAnchor = new GPoint(MainPointInfoXAnchor, MainPointInfoYAnchor);  // pixel point where the 'arrowpoint' of the popup box should sit	



	  
	// set up variables for creating the points on the map:
	var point = new GLatLng(FacLat ,FacLong);

	
	// Build an html variable to hold the html for the popup box when the point is clicked.
	var FacHTML = "";
	if ((FacTown != null) && (FacTown != "")) {
		FacHTML=FacName + " in " + FacTown + "<br>";
	}
	
	/////////
	// if the Main Point we are showing is a Council Facility then we can show images for it and link to FindMyNearest:
	if (MainPoint_IsFacility == 1) {
		FacHTML += "<a href=/comser/viewrecord.asp?UIN=" + ThisUIN + ">click here for information on this Facility</a><br>";
		var ImageFile = "/CouncilFacilitiesImages/"+ ThisUIN + ".jpg";
		
		// DoesImageExist function will return True or False by the Image pre-fetch in the asp code at the top of the page
		var ImageExists = DoesImageExist();

		if (ImageExists)
		{
			// image exists so add it to the popup box html, else it will just miss it out:	
				FacHTML += "<img src="+ImageFile+">";
			// also add the image to the sidebar:
				side_bar_image_html = "<img src="+ImageFile+">";
		}
		
	}
	
	if ((CType1 == "") || (CType1 == null)) {
	// these are the 2 lines of code that actually creates the map, using the icon just created:
		  var marker = createMarker(point,FacName,FacHTML)
		  map.addOverlay(marker);
		              
            // ==== Each time a point is found, extent the bounds ato include it =====
            bounds.extend(point);
            
		// add a line to the side_bar html
		var otherFacilities_side_bar_html = side_bar_html;
		side_bar_html = side_bar_image_html + "<br>";
		side_bar_html = side_bar_html + side_bar_icon_html +  FacName + "<br><br><br><br><hr>"; 
	}
	else {
		// just plot a slightly smaller EAC icon for the current facility in this view (i.e where Ctype requested):
		EACicon.iconSize = new GSize(30, 35);
		EACicon.iconAnchor = new GPoint(15, 35);  // pixel point of the icon which will point to the item
		EACicon.infoWindowAnchor = new GPoint(10, 25);  // pixel point where the 'arrowpoint' of the popup box should sit	
		  var marker = createMarker(point,FacName,FacHTML);
		  map.addOverlay(marker);
		              
            // ==== Each time a point is found, extent the bounds ato include it =====
            bounds.extend(point);
            
		// add a line to the side_bar html
		var otherFacilities_side_bar_html = side_bar_html;
		side_bar_html = side_bar_image_html + "<br>";
		side_bar_html = side_bar_html  + side_bar_icon_html + FacName + "</a><br><br><br><br><hr>";  
	} 



	Mainside_bar_html = side_bar_html;
	side_bar_html = "";



}  // end of "if (ShowAMainPoint)...."

		
	if (LenFacArray != 0) {	
		if (ShowOtherThings == 1) {
			CPside_bar_html += "<br>OTHER FACILITIES IN THIS LOCALE: <a href=" + PageAddress + "?UIN=" + ThisUIN + "&XREF=" + MainEast + "&YREF=" + MainNorth + "&Town=" + FacTown + "&Width=" + MapWidth + "&Height=" + MapHeight + "&ZoomLevel=" + MapZoomLevel  + "&ShowOthers=0> HIDE</a><br>(click facilities to toggle display on/off)<hr>";
	
		}
		else {
				CPside_bar_html += "<br>OTHER FACILITIES IN THIS LOCALE: <a href=" + PageAddress + "?UIN=" + ThisUIN + "&XREF=" + MainEast + "&YREF=" + MainNorth + "&Town=" + FacTown + "&Width=" + MapWidth + "&Height=" + MapHeight  + "&ZoomLevel=" + MapZoomLevel + "&ShowOthers=1> SHOW</a><br>(click facilities to toggle display on/off)<hr>";
		}
	}

// BUT! Maybe we need to set the zoom as determined by the bounds of the points on the map

//document.writeln(SetZoomByBounds);
if ((SetZoomByBounds == 1) && (side_bar_reqd == 1)) {
          // ===== determine the zoom level from the bounds =====
          map.setZoom(map.getBoundsZoomLevel(bounds) -1);

          // ===== determine the centre from the bounds ======
          map.setCenter(bounds.getCenter());

}
if ((SetZoomByBounds == 1) && (side_bar_reqd != 1)) {
          // ===== determine the zoom level from the bounds =====
          map.setZoom(map.getBoundsZoomLevel(bounds));

          // ===== determine the centre from the bounds ======
          map.setCenter(bounds.getCenter());

}





  // === put the assembled side_bar_html contents into the custom control ===
  if (side_bar_reqd == 1) {
	labelContainer.innerHTML = Mainside_bar_html + CPside_bar_html + Facside_bar_html;
	}

// Note: to add a hyperlink to the "header" at the top of the sidebar....
//	side_bar_html = side_bar_html + side_bar_icon_html + '<a href="javascript:myclick(' + i + ')">' + FacName + '</a><br><br><br><br><hr>'; 


}
