/******************************************************************************\
*  geoxml.js		                               by Lance Dyas          *
*  A Google Maps API Extension  GeoXml parser                                 *
*  GeoXml Parser based on my maps kml parser by Mike Williams called egeoxml  *
*  Additions include:   GML/WFS/GeoRSS/GPX expanded GE KML style support      *                                            
\******************************************************************************/

function getIconLocation(datatype, clustered) {
         iconlocation = "../images/single.png";
         
 	if (clustered == true) {
 		iconlocation = "../images/"+datatype;
 		iconlocation = iconlocation + "Cluster.png";
 	}
 	else  {
 		iconlocation = "../images/"+datatype;
 		iconlocation = iconlocation + ".png";
 	}
 	
 	return iconlocation;
}
function generateHeading() {

}

// Constructor
function KMLObj(title,desc) {
	this.title = title;
  	this.description = escape(desc);
  	this.marks = [];
	this.folders = [];
	}


function GeoXml(myvar,layername, layerType, sourceIsKML,showlayer,map, url, opts){
  // store the parameters
  this.layerType = layerType;
  
  this.sourceIsKML = sourceIsKML; // this is to allow us to use kml files as well as the database.  the kml files won't have [cdata] tags
  this.myvar = myvar;
  this.layername = layername;
  this.showlayer = showlayer;
  this.opts = opts || {};
  this.map = map;
  this.url = url;
  if (typeof url == "string") {
    this.urls = [url];
  } else {
    this.urls = url;
  }
 
  this.bounds = new GLatLngBounds();
  this.style = {width:2,opacity:0.75,fillopacity:0.4};
  this.lastmarker = {};   
  this.verySmall = 0.0000001;
  this.ZoomFactor = 2;
  this.NumLevels = 18;
  this.styles = []; // associative array
  this.kml = [new KMLObj("GeoXML","")];
  this.polygons = []; /*stores indexes to multi-polygons */ 
  this.polylines = []; /*stores indexes to multi-line */ 
  this.multibounds = []; /*stores extents of multi elements */
  this.folders=[];
  this.subfolders=[];
  this.allMarkers = [];
  if(this.opts.sidebarid){ this.basesidebar = this.opts.sidebarid; }
  this.wmscount = 0;
  this.labels = new GTileLayerOverlay(G_HYBRID_MAP.getTileLayers()[1]);
  }
function $(mid){ return document.getElementById(mid);}


GeoXml.prototype.createMarker = function(point,name,taggedName, desc,style,idx,instyle,visible) {
   	var myvar=this.myvar;
      
	// if this is a cluster, then desc will be "c";
	var clustered = false;
	if (desc == "c") {
	clustered = true;
	}
	var icon = getCustomIcon(this.myvar, clustered) ; 
        var iwoptions = this.opts.iwoptions || {};
         var markeroptions = this.opts.markeroptions || {};

  if (!markeroptions.icon) {
    markeroptions.icon = icon;
  }
  if (clustered == true) {
  	markeroptions.title = name;
  }
  else {
  	markeroptions.title = name + ". Click on the point for more information";
  }
  
  //markeroptions.cursor = "help";
  var m = new GMarker(point, markeroptions);
  

  // strip the header texts from the name string
  m.title = name;
  
  var obj = {"type":"point","title":name,"description":escape(desc),"visibility":visible,"x":point.x,"y": point.y};
  this.kml[idx].marks.push(obj);
  var html1 = desc; //createInfo(this.layername,taggedName,desc);
  var html2 = generateHeading();
  var html3 = getInfoCloseButton();
  //var html3 = "";
  
// listener behaviour will differ depending on the nature of
// the point - is it a cluster?
if (name == "Click to Zoom in for Details") {
  GEvent.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
    	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 );
			}
			else {
				map.setCenter(this.getPoint(), map.getZoom()+1 );
			}
		}
		else {
			// do nothing for now
		}
	
    } // startcapture = false
  });

} // this was a cluster point
else  {
	GEvent.addListener(m, "click", function(point) {
	    if (startCapture == false ) {
		    eval(myvar+".lastmarker = m");
		try {
			if(!point){ 
				point=this.getPoint(); 
			} 
		}
		catch (e) {}
		var lat = point.lat();
		var lng = point.lng();
		showInfo(html1,html2,html3,lat,lng)
	     } // startcapture = false
	}); // end of the listener function
} // this is not a cluster point



  	GEvent.addListener(m,"mouseover", function(point) {
		try {if(!point){ point=this.getPoint(); } }
		catch (e) {}
  	} );
	GEvent.addListener(m,"mouseout", function(point) {
		try {if(!point){ point=this.getPoint(); } }
		catch (e) {}
	} );


  var nhtml = "";
  var parm;
  //this.overlayman.AddMarker(m, name,idx, parm, visible);
  this.allMarkers.push(m);
  if (visible) {
	  map.addOverlay(m);
  }


};





GeoXml.prototype.toggleFolder = function(i){

	}


GeoXml.prototype.toggleContents = function(i,show){
 	
// test - simply get all markers and remove from the map or add to the map?
if (show) {
	for (var i = 0; i < this.allMarkers.length; i++) {
		this.map.addOverlay(this.allMarkers[i]);
	}
}
else {
	for (var i = 0; i < this.allMarkers.length; i++) {
		try  {
			this.map.removeOverlay(this.allMarkers[i]);
		}
		catch (e) {
		}
	}
}
 	
 	

	}; // end of function 





// Request to Parse an XML file

GeoXml.prototype.parse = function(titles) {
 
 var that = this;
 var names =[];
 if(typeof titles !="undefined"){
 if(typeof titles!= "string") {
 	names = titles;
	}
 else {
	// we have more than one type of data in the returned document?? cde
	names = titles.split(",");
	}
}
 that.progress += that.urls.length;
 for ( var u=0; u<that.urls.length; u++) {
	   var title = names[u];
	if(typeof title =="undefined" || !title || title =="null" ){
	  	var segs = that.urls[u].split("/");
		title = segs[segs.length-1];
	}
   	var re = /\.js$/i;
 	that.loadXMLUrl(this.urls[u], title);	
 }
};


var currdeschead = "";

GeoXml.prototype.handlePlacemark = function (mark, idx, depth, fullstyle) {
     var that = this;
     var desc, title, name, style;
     title = "";
     desc = "";
     var styleid = 0;
     var lat, lon;
     
     //alert(this.layername + " "+this.sourceIsKML);
     
     	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 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 = GXml.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 = GXml.parse(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 = GXml.value(pos.item(p))+" ";
				var cor = nv.split(' ');
				var node = GXml.parse("<coordinates>"+cor[0]+","+cor[1]+"</coordinates>");
				if(coordset.push)coordset.push(node); 
				}
			}
	    }


	var coords = "";
	var point_count =0;
	var box_count=0;
	var line_count=0;
	var poly_count=0;
 	for (var ln = 0; ln < mark.childNodes.length; ln++) {
		var nn = mark.childNodes.item(ln).nodeName;
		var nv = GXml.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 stuff
					  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 "title":
				
				//?? appears that firefox uses title to identify an object
				// whereas IE uses name???
				title = nv;
				// strip the CDATA stuff
				title = title.substr(9,name.length - 9); 
				title = title.substr(0, name.length - 3);
				
				var taggedName = title;
				
				
				// strip the H2 stuff
				  var newName = title.replace("<h2>","");
				  newName = newName.replace("</h2>","");
				  newName = newName.replace("<h3>","");
				  newName = newName.replace("</h3>","");
				title = newName;
				if(title.length+depth > this.maxtitlewidth)this.maxtitlewidth = title.length+depth;
				break;
			case "desc":
			case "description":
				desc += nv;
				// strip out the CDATA tags that we added to 
				// allow us to process invalid HTML data 
				// replace(RegExp("<","g"),'&lt;');
				if (this.sourceIsKML == false) {
					desc = desc.substr(9,desc.length - 9); 
					desc = desc.substr(0, desc.length - 3);
				} else {
					desc = "<h3>Description</h3>"+desc;
				
				}
				
				// now split out any next/previous buttons javascript used for photo
				readonlyhtml = desc.split("|XX|");
				
				var scriptsource = readonlyhtml[1];
				
				if (scriptsource) {	
				
					if (scriptsource.length > 0) {
						// we will only have source info if there is a photo
					//  	alert(scriptsource);
						var headID = document.getElementsByTagName("head")[0];
						var newScript = document.createElement('script');
						newScript.type = 'text/javascript';
						newScript.text = scriptsource;
						headID.appendChild(newScript);
					   }
				}
				desc = readonlyhtml[0];
				
				if(desc.match(/<(\s)*img/i)){
					var preload = document.createElement("span");
     					preload.style.visibility = "visible";
					preload.style.position = "absolute";
					preload.style.left = "-1200px";
					preload.style.top = "-1200px";
					//preload.style.zIndex = this.overlayman.markers.length; 
     					document.body.appendChild(preload);
					preload.innerHTML = desc;
					}
				
				break;
			case "visibility":
 				if(nv == "0")visible = false;
				break;
			case "href":
			case "link":
				desc += "<p><a target='_blank' href='"+nv+"'>link</a></p>";
				break;
			case "author":
				desc += "<p><b>author:</b>"+nv+"</p>";
				break;
			case "time":
				desc += "<p><b>time:</b>"+nv+"</p>";
				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 "box":
				box_count++;processme = true;break;
			case "polygon":
				poly_count++;processme = true;break;
				break;
			case "styleurl":
				styleid = nv;
			 	break;
			case "stylemap" :
				/*var found = false;
				var node = mark.childNodes.item(ln);
				for(var j=0;(j<node.childNodes.length && !found);j++){ 
					var pair = node.childNodes[j];
					for(var k =0;(k<pair.childNodes.length && !found);k++){
						var pn = pair.childNodes[k].nodeName;
						if(pn == "Style"){
							style = this.handleStyle(pair.childNodes[k]);
							found = true;
							}
						}
					}*/
				break;

			case "style":
				/*style = this.handleStyle(mark.childNodes.item(ln));*/
				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 = GXml.parse("<coordinates>"+coords+"</coordinates>");
					if(coordset.push)coordset.push(node); 
					}
				}

		}
	
      if(!name && title)name = title; 

      if(fullstyle){
		style = fullstyle;
		}
      if(styleid){
		style = this.styles[styleid];
		}

     if(newcoords && typeof lat!="undefined"){
        if(lat){
		    var cs = ""+lon+","+lat+" ";
		    var node = GXml.parse("<coordinates>"+cs+"</coordinates>");
		    coordset.push(node);
		    }
		}
     var lines = [];
     for(var c=0;c<coordset.length;c++){
	      var coords = GXml.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 GLatLng(parseFloat(bits[1]),parseFloat(bits[0]));
	              //this.overlayman.folderBounds[idx].extend(point);
   		      that.createMarker(point, name, taggedName, desc, styleid, idx, style, visible);
       	      } // path.length = 1
	      else {
			//var html1= createInfo(this.layername, taggedName,desc);
			  
			    var html1 = desc; //createInfo(this.layername,taggedName,desc);
			    var html2 = generateHeading();
			    var html3 = getInfoCloseButton();
			    //var html3 = "";

			// this is a line or a polygon
		      // Is this a polyline/polygon?
			// Build the list of points
			var points = [];
			var pbounds = new GLatLngBounds();
			for (var p=0; p<path.length-1; p++) {
				 var bits = path[p].split(",");
				 var point = new GLatLng(parseFloat(bits[1]),parseFloat(bits[0]));
				 points.push(point);
			 }
			lines.push(points);
			var linestring=mark.getElementsByTagName("LineString");
			if(linestring.length <1){
				linestring=mark.getElementsByTagName("gml:LineString");
				}
			if (linestring.length || line_count>0) {
				// add the line to the map here
				//drawColour
				//var theLine = new GPolyline(points,"#000000", 2,1);
				var theLine = new GPolyline(points,drawColour, 2,1);
				
				var vertices = parseInt(theLine.getVertexCount()/2);
				var lat = theLine.getVertex(vertices).lat();
				var lng = theLine.getVertex(vertices).lng();
				
				GEvent.addListener(theLine, "click", function() {
				    // this should only work if we are not capturing data ..
				    if (startCapture == false ) {
					try {
						if(!point){ 
							point=this.getPoint(); 
						} 
					}
					catch (e) {}
					//var lat = point.lat();
					//var lng = point.lng();
					showInfo(html1,html2,html3,lat,lng)

				    } // startcapture = false
				  });
				  this.allMarkers.push(theLine);
				  if (visible) {
					  map.addOverlay(theLine);
				  }
			}
			var polygons=mark.getElementsByTagName("Polygon");
			if(polygons.length <1){
				polygons=mark.getElementsByTagName("gml:Polygon");
				}
			if (polygons.length || poly_count>0) {
				// add the polygon to the map here
				// get the colour code ...
				//var thePoly = new GPolygon(points,"#000000",2,1,"#ff0000");
				var thePoly = new GPolygon(points,drawColour,2,1,drawColour);
				
				
				  GEvent.addListener(thePoly,"click", function() {
				      if (startCapture == false ) {
						try {
							if(!point){
								point=this.getPoint();
							}
						}
						catch (e) {}
						var lat = point.lat();
						var lng = point.lng();
						showInfo(html1,html2,html3,lat,lng)
				      } // startcapture = false
				    });
				 this.allMarkers.push(thePoly);   
				 if (visible) {
					map.addOverlay(thePoly);
				}
			}
		}
	}
    };
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;
	}; 
GeoXml.prototype.processKML = function(node, marks, title, sbid, depth) {  
	var that = this;
	//if (node.nodeName == "kml")icon = this.docicon;
        //if (node.nodeName == "Document" )icon = this.kmlicon;
	//if (node.nodeName == "Folder")icon = this.foldericon;
	
	// 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) {
			//alert(this.myvar + " " + this.showlayer);
			//document.getElementById(this.myvar).checked = false;
			//document.getElementById(this.myvar).click(); // = false;
			//this.myvar.toggleContents(1,false);
			visible = false;
		}
		else  {
			visible = true;
		}

	//var 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 "name":  
			case "title": 
				var title = GXml.value(nextn);
				if(title.length + depth > this.maxtitlewidth){ this.maxtitlewidth = title.length+depth;	}
			 	break;
			case "Folder" :
			
			case "Document" :
				sf.push(nextn); 
				break;
			case  "Description":
				var desc = GXml.value(nextn);
				break;
			case "open":
				if(GXml.value(nextn) == "1") open = true;
				if(GXml.value(nextn) == "0") open = this.forcefoldersopen;
				break;
			case "visibility":
				if(GXml.value(nextn) == "0") visible = false;
				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 = this.overlayman.folders.length;
	var idx = this.folders.length;

  	folderid = this.createFolder(idx, title, sbid, icon, desc, snip, open, visible);
 

	for(var i=0;i<pm.length;i++) {
		//this.handlePlacemark(pm[i], idx, depth+1);
		this.handlePlacemark(pm[i], 0, 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.processKML(sf[i], marks, title, folderid, depth+1);
				if(typeof fid =="number"){
					//this.overlayman.subfolders[idx].push(fid);
					//this.overlayman.folderBounds[idx].extend(this.overlayman.folderBounds[fid].getSouthWest());
					//this.overlayman.folderBounds[idx].extend(this.overlayman.folderBounds[fid].getNorthEast());
				}
		}
	if(fc || pm.length || boundsmodified){
		//this.bounds.extend(this.overlayman.folderBounds[idx].getSouthWest());
		//this.bounds.extend(this.overlayman.folderBounds[idx].getNorthEast());
		}
	return idx;
	};


GeoXml.prototype.processing = function(xmlDoc,title, latlon, desc, sbid) {


// the processing here will depend if it is a map layer or a search query


if (this.layerType == "map" ) {
	
    //this.overlayman.miStart = new Date();
    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 bar = $(this.basesidebar);
	//if(bar)bar.style.display="";
	//var idx = this.overlayman.folders.length;
	var fid = this.processKML(root, marknames, title, this.basesidebar, 0);	
	//this.kml[0].folders.push(idx);
	
	
    }  // basename = "kml"


    // Is this the last file to be processed?
    this.progress--;
    if (that.progress == 0) {
      GEvent.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
} //layertype is not map
else  {
	this.processSearchResults(xmlDoc);
}
};

GeoXml.prototype.processSearchResults = 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;
    if(!root){ alert("We are 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") {	
    
    	//document.getElementById("searchresults").style.display = "inline";

	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+");return false;\">";
				
				
				iconstring  = this.myvar.substr(0,this.myvar.length - 7);
				
				resultsHTML = resultsHTML + "<img style=\"width:12px;height:12px\" src='"+getIconLocation(iconstring,false)+"'/>";
				resultsHTML = resultsHTML + "<span style=\"font:12px Helvetica, sans-serif;\">" + resultName+ "</span></a><br>";
				
				
				// 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";
		}
		
	document.getElementById("searchresults").innerHTML = document.getElementById("searchresults").innerHTML+"<h3>"+ this.layername + " </h3>" + resultsHTML;
	
	// now display the search results!
	//document.getElementById("searchresults").style.display = "inline";
	
    }  // basename = "kml"
    else {
    	alert("We are sorry but we were unable to download data for: "+ this.layername);
    } // basename not kml
}

 
GeoXml.prototype.createFolder = function(idx, title, sbid, icon, desc, snippet, keepopen, visible){ 	      
		var sb = $(sbid);	
	 	folderid = this.myvar+'_folder'+ idx;
                var checked ="";
		if(visible){ checked = " checked " }
		//this.overlayman.folderhtml[folderid]="";
		var disp="display:block";
		var fw= "font-weight:normal";
 		if(typeof keepopen == "undefined" || !keepopen){
			disp ="display:none";
			fw = "font-weight:bold";
	 		}
	 	
	 	iconlocation = getIconLocation(this.myvar,false);
		if(!desc || desc ==""){
			desc = title;
			}
		//desc = escape(desc);
		//var htm = '<ul><input type="checkbox" id="'+this.myvar+''+idx+'FCB" style="vertical-align:middle" ';
		var htm = '<input type="checkbox" id="'+this.myvar+'" style="vertical-align:middle" ';
		
		
		
		htm += checked;
		//alert(this.myvar + " "+ idx);
		htm += 'onclick="'+this.myvar+'.toggleContents('+idx+',this.checked)">';
		htm += '&nbsp;<span title="'+snippet+'" id="'+this.myvar+'TB'+idx+'" oncontextmenu=\"'+this.myvar+'.saveJSON('+idx+');\" onclick="'+this.myvar+'.toggleFolder('+idx+')" style=\"'+fw+'\">';
		htm += '<img style=\"vertical-align:text-top;padding:0;margin:0\" height=\"16\" border=\"0\" src="'+iconlocation+'" /></span>&nbsp;';
		htm +=  desc + '<br><span id=\"'+folderid+'\" style="height:14px;'+disp+'"></span>';

		
		//if(sb){ sb.innerHTML = htm + sb.innerHTML; }
		if(sb){ sb.innerHTML = htm;} // + sb.innerHTML; }
		
		return folderid;
	    };
	    

// Augment GMarker so it handles markers that have been created but
// not yet addOverlayed.



GMap2.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);
	}
	
	};


GeoXml.prototype.loadXMLUrl = function (url, title, latlon, desc, idx) {
var that = this;	

// this is the actual xmlhttp call ...!
  GDownloadUrl(url, function(doc) {
		// try and convert the text before sending it to the parser ...??
		// eliminaet unwanted characters ..
				  		//var thisDate = new Date();
						//alert(title + " before " + thisDate);

	//var newdoc = stripNonValidXMLCharacters(doc);
				  		//var thisDate = new Date();
						//alert(title + " after " + thisDate);
						var newdoc = doc;
		
		that.processing(GXml.parse(newdoc),title, latlon, desc, idx)
  	    	//that.processing(GXml.parse(doc),title, latlon, desc, idx)
  	});
}




/* =================================== */
/* THIS CODE IS NOT USED */

