/******************************************************************************\
*  kml.js		                               by Claire Ellul (adapted from Lance Dyas)          *
*  A Non Google Maps-Specific KML extractor                                 *
\******************************************************************************/



// 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.xmlGetMapData = createXMLHttpRequest();
  this.markersArray = []; //  //reqd. in v3 as the removeoverlay methods do not exist - holds the markers in this layer
  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;
  //alert("the layer"+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 google.maps.LatLngBounds();
  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;
  }
function $(mid){ return document.getElementById(mid);}

//GeoXml.prototype.toggleFolder = function(i){
//
//	}


// Request to Parse an XML file
// this method makes the actual call to the server to get the data
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);	
 }
};


	    
// VERSION 3 - NO GDOWNLOAD URL SO HAD TO DO MY OWN
//GeoXml.prototype.loadXMLUrl = function (url, title, desc, idx) {
GeoXml.prototype.loadXMLUrl = function (url, title, desc) {
	 var that = this;	
	 var theTitle = title;
	 var theDesc = desc;
	 //var theIDX = idx;	
	 
	 this.xmlGetMapData.open("POST", url,true);
	 try {
	   //this.xmlGetMapData.setRequestHeader('Content-Type','text/html')
		this.xmlGetMapData.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	 }
	 catch (e) {
		// this only works in internet explorer
	 }

	 var xreq = this.xmlGetMapData;
	 that = this;
	 this.xmlGetMapData.onreadystatechange = function() {
			if (xreq.readyState != 4) {
				return;
			}
			// depending on the map type, do different things here:
			var responseText =  xreq.responseText;
			
			// strip leading space
			while (responseText.substring(0,1) == ' ')  {
        			responseText = responseText.substring(1, responseText.length);
			}
			// remove other non-space whitespace
			responseText = responseText.replace(/^\s+/g,"");
			
			if (isGoogleMap)  {
				that.processGM(xmlParse(responseText),theTitle,theDesc); 
			}
			else {
				that.processOL(xmlParse(responseText),theTitle,theDesc);
			}
	 };
	 this.xmlGetMapData.send();
};



// FUNCTIONS HERE REPLACE THE GXML FUCNTION THAT WAS AVAIL. AT V2 BUT IS NOT AT V3
// this function from: http://gmaps-samples-v3.googlecode.com/svn/trunk/xmlparsing/util.js
function xmlParse(str) {
  if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
    var doc = new ActiveXObject('Microsoft.XMLDOM');
    doc.loadXML(str);
    return doc;
  }

  if (typeof DOMParser != 'undefined') {
    return (new DOMParser()).parseFromString(str, 'text/xml');
  }

 // return createElement('div', null);
}

//FROM: http://www.geocodezip.com/scripts/GXml.js
function value(node){
   if(!node){
      return"";
   }
   var retStr="";
   if(node.nodeType==3||node.nodeType==4||node.nodeType==2){
      retStr+=node.nodeValue;
   }else if(node.nodeType==1||node.nodeType==9||node.nodeType==11){
      for(var i=0;i<node.childNodes.length;++i){
         retStr+=arguments.callee(node.childNodes[i]);
      }
   }
   return retStr;
}



// need a clear overlays method as this is not available in v3
// taken from: http://code.google.com/apis/maps/documentation/javascript/overlays.html#RemovingOverlays


// required to uncluster objects at zoom level 20 if they are on the same point!
// from: http://forums.devarticles.com/javascript-development-22/javascript-to-round-to-2-decimal-places-36190.html
function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}


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 toggleContents(i, show) {
	if (isGoogleMap) {
		toggleContentsGM(i,show);
	}
	else {
		toggleContentsOL(i, show);
	}
}

function moveMapSearchLocation(lat,lng) {
	if (isGoogleMap) {
		moveMapSearchLocationGM(lat,lng);
	}
	else {
		moveMapSearchLocationOL(lat,lng);
	}
}


function getMapInstance() {
	// return the instance of the map object - which will depend on whether this is a google map or not
	if (isGoogleMap) {
		return getMapGM();
		
	}
	else {
		return getMapOL();
	}
}


GeoXml.prototype.createFolder = function(idx, title, sbid, icon, desc, snippet, keepopen, visible){ 	      
		var sb = $(sbid);	
	 	folderid = this.myvar+'_folder'+ idx;
	 	//alert(folderid);
	 	//folderid = this.myvar+'_folder';
                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);
	 	//alert(iconlocation);
		if(!desc || desc ==""){
			desc = title;
			}
		var htm = '<input type="checkbox" id="'+this.myvar+'" style="vertical-align:middle" ';
		
		htm += checked;
		htm += 'onclick="'+this.myvar+'.toggleContents(1'+',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; }
		
		return folderid;
	    };
GeoXml.prototype.toggleContents = function (i,show) {
	if (isGoogleMap === true) {
		this.toggleContentsGM(1,show);
	}
	else {
		this.toggleContentsOL(1,show);
	}

};
	    
GeoXml.prototype.generateHeading = function() {
	var htmlheading = "<h3 class='mapcategory'>" + this.layername + "</h3>";
	return htmlheading;
}
	    
/*	  function clearOverlays() {
	    //if (markersArray) {
	    //  for (i in markersArray) {
	    //    markersArray[i].setMap(null);
	    //  }
	    //}
	  }
*/

