// URL - Added by KC
var doFirstPopup=0;
// URL-End
GeoXml.prototype.processGM = function(xmlDoc,title, desc) {
	// the processing here will depend if it is a map layer or a search query
	if (this.layerType == "map" ) {
		this.processGMMapResultsGM(xmlDoc,title, desc);
	} //layertype is not map
	if (this.layerType == "search" ) {
		this.processSearchResultsGM(xmlDoc);
	}

	if (this.layerType == "globalSearch" ) {
		this.processGlobalSearchResultsGM(xmlDoc);
	}

};

GeoXml.prototype.processGMMapResultsGM = function (xmlDoc, title, desc) {

	    if(!desc)desc = title;
	    var that = this;
	    //if(!sbid)sbid = 0;

	    var root = xmlDoc.documentElement;
	    if(!root){ 
		alert("We are sorry but we were unable to download data for: "+ this.layername +"\n\nMove the map to try again"); 
		//var sb = $(sbid);	
		//if(sb){ sb.innerHTML = "";} // + sb.innerHTML; }
		return 0; 
	    }  // no document found
	    var placemarks = [];
	    basename = root.nodeName;
	    var bases = basename.split(":");
	    if(bases.length>1){basename = bases[1];
	    }  // bases length greater than 1
	    if(basename == "kml") {	
		if(!title)title = name;
		this.title = title;
		if(title.length >this.maxtitlewidth){
			this.maxtitlewidth = title.length;
		} // this.maxtitlewidth
		var marknames = ["Placemark"];
		var fid = this.processKMLGM(root, marknames, title, this.basesidebar, 0);	
	    }  // basename = "kml"


	    // Is this the last file to be processed?
	    this.progress--;
	    if (that.progress == 0) {
	      google.maps.event.trigger(that,"parsed");
		// now switch layers on or off as required...
		// should the layer be on or off?
		if (this.showlayer == false) {
			document.getElementById(this.myvar).checked = false;
		}

	      if(!this.opts.sidebarid){
		//this.mb.showMess("Finished Parsing",1000);
	      }  // not this.opts.sidebarid
	    } // that.progress = 0
}



//GeoXml.prototype.createMarkerGM = function(point,name,taggedName, desc,style,idx,instyle,visible,recordid,tablename) {

//URL-Altered by KC markerid,markertable were added
GeoXml.prototype.createMarkerGM = function(point,name, taggedName, desc, recordid,tablename,visible,markerid,markertable){
//URL-End 
        var myvar=this.myvar;
   	var thislat = point.lat();
   	var thislng = point.lng();
	
	// if this is a cluster, then desc will be "c";
	var clustered = false;
	if (desc == "c") {
		clustered = true;
	}
   	
      // new code for UCL and other sites - if we are at zoom level 20, then check that this 
      // point doesnt overlap any others
      // if it does, offset it slightly
	if (map.getZoom() == 20) {
		for (var thepnt = 0; thepnt < parseInt(map.markers.length); thepnt++) {
			try {
				if (map.markers[thepnt].getPosition()) {   // this is a point - the line and polygon use getpath
					if ((roundNumber(thislat,4) == roundNumber(map.markers[thepnt].getPosition().lat(),4))) {   
						if ((roundNumber(thislng,4) == roundNumber(map.markers[thepnt].getPosition().lng(),4))) {
							//alert("markers are the same location");
							// move the point
							//alert("this lng "+thislng);
							//thislng = parseFloat(thislng) - parseFloat(0.00003);
							// relocate teh point next to the one it is over
							// keep a little element of overlap between the markers
							thislng = parseFloat(map.markers[thepnt].getPosition().lng()) - parseFloat(0.00002);
							
							
							// reset teh lat so that it is identical - so that the points appear in a very straight line and are
							// obvioulsy close to eachother
							thislat = map.markers[thepnt].getPosition().lat();
							
							//alert("this lng 2 "+thislng);
						}
						
					}
				}
			}
			catch (e) {} // this is a line or poly so ignore
		}
	}
	
	var newpoint = new google.maps.LatLng(parseFloat(thislat), parseFloat(thislng));
	var imagelocation = getCustomIcon(this.myvar, clustered) ; 

	var icon = new google.maps.MarkerImage(imagelocation,
        new google.maps.Size(20, 20),
        // The origin for this image is 0,0.
        new google.maps.Point(0,0),
        // The anchor for this image 
        new google.maps.Point(10, 10));

	  var m = new google.maps.Marker({position:newpoint, icon: icon});
	  if (visible) {
		m.setMap(map);
	  }
	  else {
		m.setMap(null);
	  }
	  // strip the header texts from the name string
	  m.title = name;

	  //var obj = {"type":"point","title":name,"description":escape(desc),"visibility":visible,"x":newpoint.x,"y": newpoint.y};
	  //this.kml[idx].marks.push(obj);
  
		// listener behaviour will differ depending on the nature of
		// the point - is it a cluster?
		if (name == "Click to Zoom in for Details") {
		  google.maps.event.addListener(m, "click", function() {
		    // this should only work if we are not capturing data ..
		    if (startCapture == false ) {
			     // if this is a cluster marker, offer the user the opportunity to zoom in
			isSearchMove = false;
			var answer = confirm ("There are multiple points in this area. Zoom in to see more details?")
				if (answer) {
					// centre on the point
					if (map.getZoom() < 13) {
						//map.setCenter(this.getPoint(), map.getZoom() + 3 );
						map.setCenter(this.getPosition());
						map.setZoom(map.getZoom()+ 3 );
					}
					else {
						//map.setCenter(this.getPoint(), map.getZoom()+1 );
						map.setCenter(this.getPosition());
						map.setZoom(map.getZoom()+1); 
					}
				}
				else {
					// do nothing for now
				}

		    } // startcapture = false
		  });

		} // this was a cluster point
                
		//URL-Added by KC              
              else if (recordid == markerid  && tablename.toLowerCase() == markertable && doFirstPopup < 3) {
                    
                    if (map.getCenter() != m.getPosition()) {
                      
                        map.setCenter(m.getPosition());
                        map.setZoom(map.getZoom(5)); 
                    }

                    google.maps.event.addListener(m, "click", function(point) {
		    // this should only work if we are not capturing data ..
		    if (startCapture == false ) {
			     // if this is a cluster marker, offer the user the opportunity to zoom in
			isSearchMove = false;
                        
                        // need to use this counter as the code works as follows:
                        // 0.  finds the recordid == marker id match
                        // 1.  does the data retrieval for all the data BEFORE moving the map to the correct position, because this is part of a moveend event
                        // i.e. the map gets all the data in the middle of this moveend event and doesnt' do the next move until after all the data is retrieved
                        // the second zoom (i.e. to the new centre) will start the data retrieval all over
                        // and it is on this data retrieval that we want the info box to pop up - hence the counter doFirstPopup
                        
                                                                        doFirstPopup=doFirstPopup+1;
                                                                        //  alert(doFirstPopup);               
                        infolat = this.getPosition().lat();
                        infolng = this.getPosition().lng();
                        getInfo(recordid, tablename);
					}
		  });
                    google.maps.event.trigger(m, "click");
                    
                    // claire - set the boolean to show that the info box is visible
                    infodisplayed = true;
                    
                  } 
    //URL-End by KC      
                
                else  {
			
			google.maps.event.addListener(m, "click", function(point) {
			    isSearchMove = false;
			    if (startCapture == false ) {
				eval(myvar+".lastmarker = m");
				// set the global position variables that will 
				// tell the info window where to pop up
				infolat = this.getPosition().lat();
				infolng = this.getPosition().lng();
				getInfo(recordid,tablename);
			     } // startcapture = false
			}); // end of the listener function
		} // this is not a cluster point

		google.maps.event.addListener(m,"mouseover", function(point) {
			try {if(!point){ point=this.getPoint(); } }
			catch (e) {}
		} );
		google.maps.event.addListener(m,"mouseout", function(point) {
			try {if(!point){ point=this.getPoint(); } }
			catch (e) {}
		} );
		  var nhtml = "";
		  var parm;
		  this.markersArray.push(m);
		  map.markers.push(m);
};



GeoXml.prototype.toggleContentsGM = function(i,show){
	if (show) {
		for (var i=0;i<this.markersArray.length;i++) {
			this.markersArray[i].setMap(map);
		}
	}
	else {
		for (var i=0;i<this.markersArray.length;i++) {
			this.markersArray[i].setMap(null);
		}


	}
}; // end of function 



GeoXml.prototype.handlePlacemarkGM = function (mark, idx, depth, fullstyle) {

     var that = this;
     var desc, title, name, style;
     title = "";
     desc = "";
     var styleid = 0;
     
     //URL-Added by KC
     var markerid = this.getMarkerId();
     var markertable = this.getMarkerTable();
     //URL-End
     
     var lat, lon;
     	var drawColour = getColour(this.myvar);
     	
     	var visible = true;
     		// now switch layers on or off as required...
     		// should the layer be on or off?
     		if (this.showlayer == false) {
     			visible = false;
     		}
     		else  {
     			visible = true;
     		}

     var newcoords = false;
     var l = mark.getAttribute("lat");
     if(typeof l!="undefined")lat = l;
     l = mark.getAttribute("lon");
     if(typeof l!="undefined"){
		newcoords = true;
		lon = l;
		}
	var poly_count;
	var line_count;
     var coordset=mark.getElementsByTagName("coordinates");
	if(coordset.length <1){
	    coordset=mark.getElementsByTagName("gml:coordinates");
	    }
	if(coordset.length <1){
	   	coordset = [];
	    	var poslist =mark.getElementsByTagName("gml:posList");
		for(var l =0;l<poslist.length;l++){
			var coords = " ";
			var plitem = value(poslist.item(l)) + " ";
			var cor = plitem.split(' ');
			for(var cc=0;cc<(cor.length-1);cc++){
					if(cor[cc] && cor[cc]!=" " && !isNaN(parseFloat(cor[cc]))){
						coords += ""+parseFloat(cor[cc])+","+parseFloat(cor[cc+1]);
						coords += " ";
						}
					cc++;
					}
			if(coords){
 				if(poslist.item(l).parentNode && (poslist.item(l).parentNode.nodeName == "gml:LineString") )line_count++;
					else poly_count++;
				var cm = "<coordinates>"+coords+"</coordinates>";
				var node = xmlParse(cm);
				if(coordset.push)coordset.push(node); 
				}
			}

		var pos = mark.getElementsByTagName("gml:pos");
		if(pos.length <1)pos = mark.getElementsByTagName("gml:pos");
		if(pos.length){
			for(var p=0;p<pos.length;p++){
				var nv = value(pos.item(p))+" ";
				var cor = nv.split(' ');
				var node = xmlParse("<coordinates>"+cor[0]+","+cor[1]+"</coordinates>");
				if(coordset.push)coordset.push(node); 
				}
			}
	    }


	var coords = "";
	var point_count =0;
	var box_count=0;
 	for (var ln = 0; ln < mark.childNodes.length; ln++) {
		var nn = mark.childNodes.item(ln).nodeName;
		var nv = value(mark.childNodes.item(ln));
		var ns = nn.split(":");
		var base;
		if(ns.length>1)base = ns[1].toLowerCase();
			else base = ns[0].toLowerCase();	
		
		processme = false;
		switch(base){
			case "name": 
				name = nv;
				// strip the CDATA stuff
				if (this.sourceIsKML == false ) {
					name = name.substr(9,name.length - 9); 
					name = name.substr(0, name.length - 3);
					// strip any h2 stuff
					var taggedName = name;


					// strip the H2 stu
					  var newName = name.replace("<h2>","");
					  newName = newName.replace("</h2>","");
					  newName = newName.replace("<h3>","");
					  newName = newName.replace("</h3>","");
					name = newName;
					if(name.length+depth > this.maxtitlewidth)this.maxtitlewidth = name.length+depth;
				} else {
					taggedName = "<h2>Name</h2>"+name;
				}
				
				break;
			case "recordid":
				var recordid = nv;
				break;
			case "tablename":
				var tablename = nv;
				break;
			case "description":
				desc = nv;
				break;
			case "lat":
				lat=nv; 
				break; 
			case "long":
				lon=nv; 
				newcoords = true;
				break;
			case "point":
				point_count++;
                                processme = true;
				break;
			case "line":
				line_count++;processme = true;
				break;
			case "polygon":
				poly_count++;processme = true;break;
				break;
			}
			if(processme){
				var cor = nv.split(' ');
				coords = "";
				for(var cc=0;cc<(cor.length-1);cc++){
					if(cor[cc] && cor[cc]!=" " && !isNaN(parseFloat(cor[cc]))){
						coords += ""+parseFloat(cor[cc+1])+","+parseFloat(cor[cc]);
						if(cc>1 && cc<(cor.length-2)) coords += " ";
						}
					cc++;
					}
				if(coords !=""){
					var node = xmlParse("<coordinates>"+coords+"</coordinates>");
					if(coordset.push)coordset.push(node); 
					}
				}

		}
	
      if(!name && title)name = title; 
     if(newcoords && typeof lat!="undefined"){
        if(lat){
		    var cs = ""+lon+","+lat+" ";
		    var node = xmlParse("<coordinates>"+cs+"</coordinates>");
		    coordset.push(node);
		    }
		}
     for(var c=0;c<coordset.length;c++){
	      var coords = value(coordset[c]);
	      coords += " ";
	      coords=coords.replace(/\s+/g," "); // tidy the whitespace
	      coords=coords.replace(/^ /,"");    // remove possible leading whitespace
	      //coords=coords +" "; //ensure trailing space
	      coords=coords.replace(/, /,",");   // tidy the commas
	      var path = coords.split(" ");
	      if (path.length == 1 || path[1]== "") {
	      		// this is a point
	              var bits = path[0].split(",");
	              var point = new google.maps.LatLng(parseFloat(bits[1]),parseFloat(bits[0]));
   		      //that.createMarkerGM(point, name, taggedName, desc, styleid, idx, style, visible,recordid,tablename);
   		      //URL-Altered by KC
                      that.createMarkerGM(point,name, taggedName, desc, recordid,tablename,visible, markerid,markertable);
                      //URL-END
            } // path.length = 1
	      else {
	      	   
			// this is a line or a polygon
			// Build the list of points
			that.createLinePolygon(mark,path,name, taggedName, desc, recordid,tablename,visible);
	     }
     }

};
//URL-Added by KC

GeoXml.prototype.getMarkerId = function getMarkerId() {
		var sPath = window.location;
		var paths = String(sPath).split("?");  // this gets the parameter list
		
		// now split the parameter list by the & 
		if (paths[1])  {
			var parameters = paths[1].split("&");
			var i;
			var markerid = "";
			for (i=0;i<parameters.length;i++) {
				var paramstring = parameters[i];
				if (paramstring.indexOf("markerid") > -1 )  {
					var markeridstring = paramstring.split("=");
					markerid = markeridstring[1];
					markerid = markerid.replace("#","");
                                        markerid = parseFloat(markerid);
//                                        markerid = "&markerid="+markerid;
				}
			}
			return markerid;
		}
		else {
			return "";
		}
}

GeoXml.prototype.getMarkerTable = function getMarkerTable() {
		var sPath = window.location;
		var paths = String(sPath).split("?");  // this gets the parameter list

		// now split the parameter list by the &
		if (paths[1])  {
			var parameters = paths[1].split("&");
			var i;
			var markertable = "";
			for (i=0;i<parameters.length;i++) {
				var paramstring = parameters[i];
				if (paramstring.indexOf("markertable") > -1 )  {
					var markertablestring = paramstring.split("=");
					markertable = markertablestring[1];
					markertable = markertable.replace("#","");
//                                        markertable = "&markertable="+markertable;
				}
			}
			return markertable;
		}
		else {
			return "";
		}
}

//URL-End

GeoXml.prototype.createLinePolygon = function (mark,path, name, taggedName, desc, recordid, tablename,visible) {
			var points = [];
			var lines = [];
			var drawColour = getColour(this.myvar);
			var pbounds = new google.maps.LatLngBounds();
			for (var p=0; p<path.length-1; p++) {
				 var bits = path[p].split(",");
				 var point = new google.maps.LatLng(parseFloat(bits[1]),parseFloat(bits[0]));
				 points.push(point);
			 }
			lines.push(points);
			var linestring=mark.getElementsByTagName("LineString");
			var theLine = new google.maps.Polyline({path:points,strokeColor:drawColour, strokeWeight:2,strokeOpacity:1});
			var vertices = parseInt(points.length);
			var lat = points[0].lat();
			var lng = points[0].lng();

			  if (visible) {
				theLine.setMap(map);
			  }
			  else {
				theLine.setMap(null);
			  }

			google.maps.event.addListener(theLine, "click", function() {
			    // this should only work if we are not capturing data ..
			    isSearchMove = false;
			    if (startCapture == false ) {
				try {
					if(!point){ 
						//point=this.getPoint(); 
						point = this.getPath();
					} 
				}
				catch (e) {}
				infolat = point.lat();
				infolng = point.lng();
				getInfo(recordid,tablename);

			    } // startcapture = false
			  });
			  this.markersArray.push(theLine);
			  map.markers.push(theLine);


			var polygons=mark.getElementsByTagName("Polygon");
			if (polygons.length) {
				// add the polygon to the map here
				// get the colour code ...
				var thePoly = new google.maps.Polygon({paths:points,strokeColor:drawColour,strokeWeight:2,strokeOpacity:1,fillColor:drawColour,fillOpacity:0.2});
				  google.maps.event.addListener(thePoly,"click", function() {
				      isSearchMove = false;
				      if (startCapture == false ) {
						try {
							if(!point){
								point = this.getPath();  
							}
						}
						catch (e) {}
						infolat = point.lat();
						infolng = point.lng();
						getInfo(recordid,tablename);
				      } // startcapture = false
				    });
				 this.markersArray.push(thePoly);
				 map.markers.push(thePoly);
				 if (visible) {
					//map.addOverlay(thePoly);
					thePoly.setMap(map);
				}
				else {
					thePoly.setMap(null);
				}

			}

};
GeoXml.prototype.processKMLGM = function(node, marks, title, sbid, depth) {  
	var that = this;
	// use the same icon as on screen for the layer
	icon = getCustomIcon(this.myvar, false);
	
	var pm = [];
	var sf = [];
	var desc= "";
	var desc = that.layername;
	var snip ="";
	var i;
	//var open = that.forcefoldersopen;
	var visible = true;
	// depending on whether the layer is on or off ..!
		// now switch layers on or off as required...
		// should the layer be on or off?
		if (this.showlayer == false) {
			visible = false;
		}
		else  {
			visible = true;
		}

	var boundsmodified = false;
        networklink = false;
	var url;
	var ground = null;
	var opacity = 1.0;
	var wmsbounds;
	var makewms = false;
	var wmslist = [];
	
	for (var ln = 0; ln < node.childNodes.length; ln++) {
		var nextn = node.childNodes.item(ln);
		var nn = nextn.nodeName;
		var nv = nextn.nodeValue;
		
		switch (nn) {
			case "title": 
				var title = value(nextn);
				if(title.length + depth > this.maxtitlewidth){ this.maxtitlewidth = title.length+depth;	}
			 	break;
			case "Document" :
				sf.push(nextn); 
				break;
			default:
				for(var k=0;k<marks.length;k++){
					if(nn == marks[k]){
						pm.push(nextn);
					}	// nn == makrs
				} // marks.length
		} // switch
	} // nodes.childnode.length	

	var folderid;
	
	var idx = 0;
	if ((this.folders.length) == 0) {
	  	folderid = this.createFolder(idx, title, sbid, icon, desc, snip, open, visible);
 		this.folders.push(folderid);
	}
	else {
		folderid = this.folders[0];
	}
 
 
	//alert(this.markersArray.length);
	for (var i = this.markersArray.length -1; i = 0; i--) {
		this.markersArray.pop();
	}
	
	
	for(var i=0;i<pm.length;i++) {
		this.handlePlacemarkGM(pm[i], idx, depth+1);
		}
	var fc = 0;

	
	// this is the bit that loads the actual data for display!
		for(i=0;i<sf.length;i++) {
			var fid = this.processKMLGM(sf[i], marks, title, folderid, depth+1);
		}
	return idx;
};


GeoXml.prototype.processGlobalSearchResultsGM = function(xmlDoc) {


// we need to put an entry for each result, with a hotlink that opens the minisite and zooms to the correct location??
// to centre the map on the point

    
    var root = xmlDoc.documentElement;
    var theTableName = this.myvar.replace("_search","");
    if(!root){ 
    	alert("We are very sorry but we were unable to download data for: "+ this.layername); return 0; 
    }  // no document found
    var placemarks = [];
    basename = root.nodeName;
    var bases = basename.split(":");
    if(bases.length>1){
    	basename = bases[1];
    }  // bases length greater than 1
    if(basename == "kml") {	
	var node=root;
	// now process the search results
		var that = this;
		var resultsHTML = "";
		
		//get the next level node down ..
		node = node.childNodes.item(0);
		for (var ln = 0; ln < node.childNodes.length; ln++) {
			var nextn = node.childNodes.item(ln);
			var nn = nextn.nodeName;
			var nv = nextn.nodeValue;
			
			// only add the result if it has coordinate information with it...
			var coordString = nextn.childNodes.item(2).childNodes.item(0).childNodes.item(0).nodeValue;
			if (coordString != ",") {
				// add the result onto the list
				// add as a text item
				// build up the parameter string to pass to goto result
				// we need the layer name and the coordinates
				var resultName = nextn.childNodes.item(0).childNodes.item(0).nodeValue;
				// now strip the CDATA tags away
				resultName = resultName.substr(9,resultName.length - 9); 
				resultName = resultName.substr(0, resultName.length - 3);
				
				var resultID = nextn.childNodes.item(1).childNodes.item(0).nodeValue;

				//a href=\"javascript:gotoLoginPage()\">
				
				resultString = coordString ;
	
				//resultsHTML = resultsHTML + "<li><a href=\"\#\" onclick=\"gotoOverviewResult("+resultString+",'"+ this.layername+"',"+ resultID+");return false;\">";

				resultsHTML = resultsHTML + "<li><a href=\"\#\" onclick=\"gotoOverviewResult("+resultString+",'"+ this.layername+"',"+ resultID+",'"+theTableName+"');return false;\">";
				resultsHTML = resultsHTML + resultName + "</a></li>";
	
				// this code required due to long response time for ie7 whereas firefox displays
				// immediate results XXXXX
				

			} // nodevalue is not null			
		} // nodes.childnode.length	
		if (resultsHTML == "") {
			resultsHTML = "No matches found";
		}
		else {
			
			resultsHTML = "<ul>"+resultsHTML + "</ul>";
		
		}


	iconstring  = this.myvar.substr(0,this.myvar.length - 7);
	var imageString = "<img style=\"width:12px;height:12px\" src='"+getIconLocation(iconstring,false)+"'/>";
	
	//document.getElementById("search_results").innerHTML = "<li>"+document.getElementById("search_results").innerHTML+"<h3>"+imageString+ this.layername + " </h3>" + resultsHTML+"</li>";
	//document.getElementById("search_results"+this.layername).innerHTML = "<li>"+imageString+ this.layername + " </h3>" + resultsHTML+"</li>";
	if (theTableName) {
		var divString = "search_results"+theTableName;
		//alert (divString);
		document.getElementById(divString).innerHTML = "<li>"+imageString+ this.layername + " </h3>" + resultsHTML+"</li>";
	}

	
	
    }  // basename = "kml"
    else {
		if(this.layername != "MiniSites")
		{
			alert("We are sorry but we were unable to download data for: "+ this.layername);
		}
    } // basename not kml
  
}

function getMapGM()  {
	//return the instance of the map object for google maps
	// in this case the variable is called map
	return map;
}


GeoXml.prototype.processSearchResultsGM = function(xmlDoc) {

// we need to put an entry for each result, with a hotlink that moves the map
// to centre the map on the point

    
    var root = xmlDoc.documentElement;
    var theTableName = this.myvar.replace("_search","");

    if(!root){ alert("We are very sorry but we were unable to download data for: "+ this.layername); return 0; 
    }  // no document found
    var placemarks = [];
    basename = root.nodeName;
    var bases = basename.split(":");
    if(bases.length>1){basename = bases[1];
    }  // bases length greater than 1
    if(basename == "kml") {	
    
	
	var node=root;
	// now process the search results
		var that = this;
		var resultsHTML = "";
		
		//get the next level node down ..
		node = node.childNodes.item(0);
		
		
		for (var ln = 0; ln < node.childNodes.length; ln++) {
			var nextn = node.childNodes.item(ln);
			var nn = nextn.nodeName;
			var nv = nextn.nodeValue;
			
			// only add the result if it has coordinate information with it...
			var coordString = nextn.childNodes.item(2).childNodes.item(0).childNodes.item(0).nodeValue;
			if (coordString != ",") {
				// add the result onto the list
				// add as a text item
				// build up the parameter string to pass to goto result
				// we need the layer name and the coordinates
				var resultName = nextn.childNodes.item(0).childNodes.item(0).nodeValue;
				// now strip the CDATA tags away
				resultName = resultName.substr(9,resultName.length - 9); 
				resultName = resultName.substr(0, resultName.length - 3);
				
				var resultID = nextn.childNodes.item(1).childNodes.item(0).nodeValue;

				//a href=\"javascript:gotoLoginPage()\">
				
				resultString = coordString ;
				
				
				//resultsHTML = resultsHTML + "<a style=\"color:#000000;\"href=\"#\" onclick=\"gotoResult("+resultString+",'"+ this.layername+"',"+ resultID+",'"+this.myvar+"');return false;\">";
				
				// as this is a search function, the name will have _search tagged on
				// we need to remove this to call the gotoResult function
				//alert(this.myvar);
				resultsHTML = resultsHTML + "<li><a href=\"\#\" onclick=\"gotoResult("+resultString+",'"+ this.layername+"',"+ resultID+",'"+theTableName+"');return false;\">";
				resultsHTML = resultsHTML + resultName + "</a></li>";
	

				
				// this code required due to long response time for ie7 whereas firefox displays
				// immediate results
				

			} // nodevalue is not null			
		} // nodes.childnode.length	
		if (resultsHTML == "") {
			resultsHTML = "No matches found";
		}
		else {
			
			resultsHTML = "<ul>"+resultsHTML + "</ul>";
		
		}
	//document.getElementById("searchresults").innerHTML = document.getElementById("searchresults").innerHTML+"<h3>"+ this.layername + " </h3>" + resultsHTML;
	iconstring  = this.myvar.substr(0,this.myvar.length - 7);
	var imageString = "<img style=\"width:12px;height:12px\" src='"+getIconLocation(iconstring,false)+"'/>";
	//document.getElementById("search_results").innerHTML = "<li>"+document.getElementById("search_results").innerHTML+"<h3>"+imageString+ this.layername + " </h3>" + resultsHTML+"</li>";
	//document.getElementById("search_results"+this.layername).innerHTML = "<li>"+imageString+ this.layername + " </h3>" + resultsHTML+"</li>";
	if (theTableName) {
		var divString = "search_results"+theTableName;
		document.getElementById(divString).innerHTML = "<li>"+imageString+ this.layername + " </h3>" + resultsHTML+"</li>";
	}
	
	
	
    }  // basename = "kml"
    else {
    	alert("We are sorry but we were unable to download data for: "+ this.layername);
    } // basename not kml
}

function gmapVars() {
	var bounds = map.getBounds();
	var theZoom = map.getZoom();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	var getVars = 'ne='+northEast.toUrlValue() +'&sw=' + southWest.toUrlValue()+'&zoom='+theZoom;
	return getVars;
	
}

function moveMapSearchLocationGM(lat,lng) {

	//zoomLevel = map.getZoom();
	zoomLevel = 17;
	// move the map
	map.setCenter(new google.maps.LatLng(lat, lng), zoomLevel);
	map.setZoom(zoomLevel);
}


function moveMapSearchLocationGMthenPopupInfo(lat,lng,id,tablename) {

	//zoomLevel = map.getZoom();
	zoomLevel = 17;
	// move the map
	map.setCenter(new google.maps.LatLng(lat, lng), zoomLevel);
	map.setZoom(zoomLevel);
	
	// now put a wait process in so that the map completes its move
	//setTimeout("getInfo("+id+","+tablename+")",2000);
	setTimeout(function() {getInfo(id,tablename);},1500);
	
	// now popup the info box
	//getInfo(id,tablename);
	
}



/* EXTENSIONS TO FUNCTIONALITY IN GOOGLE MAPS */
google.maps.Map.prototype.getObjCenter = function(){
	var container = obj = this.getContainer();
	var y = x = 0;
	if (obj.offsetParent) {
		x = obj.offsetLeft;
		y = obj.offsetTop;
		while (obj = obj.offsetParent) {
			x += obj.offsetLeft;
			y += obj.offsetTop;
		}
 	return new GPoint(x+parseInt(this.getSize().width)/2,y+parseInt(this.getSize().height)/2);
	}
	
	};



google.maps.Map.prototype.clearMarkers = function() {
    for(var i=0; i < this.markers.length; i++){
        this.markers[i].setMap(null);
    }
    this.markers = new Array();
};


google.maps.Map.prototype.markers = new Array();




/* =======================
// FOLLOWING CODE MIGHT NOT BE USED ANY MORE
*/

/*
GeoXml.prototype.makeIcon = function(tempstyle, href){
	
	if (!!href) {
          if (!!this.opts.baseicon) {
           tempstyle = new GIcon(this.opts.baseicon,href);
	   tempstyle.href = href;
          } else {
            tempstyle = new GIcon(G_DEFAULT_ICON,href);
            tempstyle.iconSize = new GSize(32,32);
            tempstyle.shadowSize = new GSize(59,32);
            tempstyle.dragCrossAnchor = new GPoint(2,8);
            tempstyle.iconAnchor = new GPoint(16,32);
  	    tempstyle.href = href;
            if (this.opts.printgif) {
              var bits = href.split("/");
              var gif = bits[bits.length-1];
              gif = this.opts.printgifpath + gif.replace(/.png/i,".gif");
              tempstyle.printImage = gif;
              tempstyle.mozPrintImage = gif;
            }
            if (!!this.opts.noshadow) {
              tempstyle.shadow="";
            } else {
              // Try to guess the shadow image
              if (href.indexOf("/red.png")>-1 
               || href.indexOf("/blue.png")>-1 
               || href.indexOf("/green.png")>-1 
               || href.indexOf("/yellow.png")>-1 
               || href.indexOf("/lightblue.png")>-1 
               || href.indexOf("/purple.png")>-1
		|| href.indexOf("/orange.png")>-1 
               || href.indexOf("/pink.png")>-1 
		|| href.indexOf("-dot.png")>-1 ) {
                  tempstyle.shadow="http://maps.google.com/mapfiles/ms/icons/msmarker.shadow.png";
              }
              else if (href.indexOf("-pushpin.png")>-1  
		|| href.indexOf("/pause.png")>-1 
		|| href.indexOf("/go.png")>-1    
		|| href.indexOf("/stop.png")>-1     ) {
                  tempstyle.shadow="http://maps.google.com/mapfiles/ms/icons/pushpin_shadow.png";
              }
              else {
                var shadow = href.replace(".png",".shadow.png");
                tempstyle.shadow=shadow;
              }
            }
          }
        }
	return tempstyle;
	}; 
*/

