var activeSystem = 0;
var throbcounter = 0;
var useLegacyLocalLoad = false;
var useGgeoXml=false;

function getInstallDir(){
    if(top.standalone){
        return "";
        }
    else {
        return publishdirectory
    }
}
var exml;
function $(mid){ return document.getElementById(mid);}
function setCallBack(val){
		if(!val) return;
		var h = /^http/i;
		$('bless').action = top.getcapproxy+"k=js";
		if(val.search(h) != -1){
			var name = val.substring(val.lastIndexOf("\\")+1);
			 locate(val); 
			}
		else {
			var re = /\.js$/i;
			if(val.search(re) != -1){
				$('callback').value = "top.exml.parseJSON";
				}
   			else {
				$('callback').value = "top.exml.parseString";
				}
			exml.mb.showMess("uploading file "+val,10000);
			$('bless').submit();
	 		$('uploadKML').style.display="none";
			}
		}
function getKML(dsrc){
	if(top.standalone){
	var file = browseForFile("Select the GeoXML file", "KML Files (*.kml)|*.kml|GML Files(*.gml)|*.gml|JSON Files(*.js)|*.js|XML Files(*.xml)|*.xml|GPX Files(*.gpx)|*.gpx|All Files (*.*)|*.*")
	var name = file.substring(file.lastIndexOf("\\")+1); 
	loadKML(file,name,null);
	return;	
		}
	else {
		var f =  $("uploadKML");
		if(f.style.display == "none") { f.style.display=""; }
			else { f.style.display="none"; }
		}
	}

function fixUrlEnd(url){
	var e = url.substring(url.length-1);
	re = /\&|\?/;
	if(!e.match(re)){
		if(url.indexOf('?')== -1){
			url += "?";
			}
		else { 
			if(url.indexOf('&')!=(url.length-1)){
				url += "&";
				}
			}
		}
	return url;
	}
 
 function serverBlessJSON (js, filename) {
     exml.mb.showMess("Downloading JSON file",4000);
     html = "<html>";
     html += "<body>";
     html += "<form method=\"post\" target=\"_self\" name=\"bless\" action=\"" + exml.proxy + "k=cml\">";
     html += "<input type=\"text\" name=\"request\" value=\"blessJSON\" >";
     html += "<input type=\"text\" name=\"fname\" value=\"" + filename + "\" >";
     html += "<input type=\"hidden\" name=\"json\" width=100 style='color:red' value =\"" +  js + "\" >";
     html += "</form>";
     html += "<sc"+"ript>document.forms['bless'].submit();</sc"+"ript>";
     html += "</body>";
     html += "</html>";
     top.frames["data1"].document.write(html);
     top.frames["data1"].document.close();
    }

function resizeKML(){
    if(exml && exml.overlayman){
	var kj = $("kjsonsave");
	if(exml.overlayman.markers.length){
	    var h = (exml.overlayman.markers.length+exml.overlayman.folders.length)*20;
	    if(exml.wmscount)h += (exml.wmscount * 100);
	    var w = 34+8*(exml.maxtitlewidth);
	    var gs = getWinSize();
	    var max = (gs.h);
	    var reduce = layerList.length*12;
	    if(w>(gs.w/2))w=gs.w/2;
	    if(reduce>(h/2)) reduce = h/2;
 	    if((h+reduce+170)>max ) { h = max - reduce - 170; }
	    var mo = $("myoverlays");
	    mo.style.height = (h + 170 + reduce) + "px";
 	    var ko = $("kml_layers");
	    ko.style.height = h +"px";
	    if(w>130){
	 	$("layerControls").style.right = "8px";
		$("layerControls").style.width = w +"px";
		if(kj)kj.style.display = "";
		mo.style.width = w + "px";
		ko.style.width = w + "px";
		}
	    }
 	else {
		if(kj)kj.style.display = "none";
		}
		}
	}
 

function makeKMLlayer(resp,titler,latlon,nzoom) {
 	if(resp.responseText.substring(0,100).indexOf("Exception")==-1){
		if(typeof exml == "undefined") {
			exml = new GeoXml("exml", map, "", {sidebarid:"kml_layers",sortbyname:false,directions:true,"title":titler,"nozoom":nzoom}); 
			}
		exml.opts.nozoom = nzoom;
		exml.title = titler;
		exml.mb.showMess("Constructing view from GeoXML...");
		exml.bounds = new GLatLngBounds();
  		exml.parseXML(resp.responseXML,titler,latlon);
		}
	else {
		exml.mb.showMess(resp.responseText,3000);
		} 
	}
function toggleOverlay(al,off){
	al = parseInt(al,10);
	var item = $('ol'+al);
	var wid;
	var i;
	var ti = $('ot'+al);
	var ol;
	if(item.checked && !off){ 
		ti.className = "layerOn";
		for(i=al; i<ovl.length; i++){
			ol = layerorder[i];
			if(layerList[ol].on){
				wid = ovl[ol];
				if(wid)map.removeOverlay(wid);
				}
			}
		layerList[al].on = true;
		for(i=al;i<ovl.length;i++){
			ol = layerorder[i];
			wid = ovl[ol];
			if(layerList[ol].on){
				map.addOverlay(wid);
				}
			}
		}
	else { 
		wid = ovl[al]; 
		layerList[al].on = false;
		if(wid)map.removeOverlay(wid); 	
		ti.className = "layerOff";
		}
	
	}
function showURL (url, h, w) {
    var win;
    if (top.main) {
        win = top.main;
        }
    else {
        win = window;
        }
    if (top.widget) {
        exml.mb.showMess("Launching default browser to " + url, 4000);
        top.widget.system('/usr/bin/open ' + url, null);
        top.widget.openURL('');
        }
    else {
        if (! h) h = 800;
        if (! w) w = 800;
        var features = "resizable=yes,scroll=yes,toolbar=no,height=" + h + ",width=" + w
                + ",status=yes,statusbar=yes";
        window.open(url, "_blank", features);
        }
    }
var localkml;

function loadKML(fpath,title,latlon,nozoom){
	if(!fpath)return;
  	var re = /\.js$/i;
	var isJSON = false
   	if(fpath.search(re) != -1){
		isJSON = true;
		}
	var xmlDoc, t;
	cmlurl = fpath;
    if (top.standalone && useLegacyLocalLoad && !top.widget) {
        if (cmlurl.substring(2, 3) == ":") {
            xmlDoc = new ActiveXObject("Msxml2.DOMDocument.4.0");
            xmlDoc.validateOnParse = false;
            xmlDoc.async = true;
            xmlDoc.load(cmlurl);
            if (xmlDoc.parseError.errorCode !== 0) {
                var myErr = xmlDoc.parseError;
                alert ("CML file appears incorrect\n" + myErr.reason + " at line:" + myErr.line );
                }
            else {
		var resp ={"responseXML":xmlDoc,"responseText":xmlDoc.xml}
		if(!isJSON) makeKMLlayer(resp,title,latlon,nozoom);
		else exml.parseJSON(resp.responseText,title, latlon);
                }
            return;
            }
        }
    var cmlreq;
    /*@cc_on @*/
    /*@if(@_jscript_version>=5)
    try{
    cmlreq=new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
    try{
    cmlreq=new ActiveXObject("Microsoft.XMLHTTP");
    }catch(E){
    alert("attempting xmlhttp");
    cmlreq=false;
    }
    }
    @end @*/
    if (! cmlreq && typeof XMLHttpRequest != 'undefined') {
        cmlreq = new XMLHttpRequest();
        }
    else {
        if (typeof ActiveXObject != "undefined") {
            cmlreq = new ActiveXObject("Microsoft.XMLHTTP");
            }
        }

    if (!top.standalone) {
        proxy = fixUrlEnd(top.getcapproxy, true);
        cmlurl = proxy + "url=" + escape(cmlurl);
        }

    var here = cmlurl;
    if(cmlreq.overrideMimeType)cmlreq.overrideMimeType("text/xml");
    cmlreq.open("GET", here, true);
    cmlreq.onreadystatechange = function () {
        switch (cmlreq.readyState) {
            case 4:
                exml.mb.showMess("Request received", 2000);
		if(isJSON){
			 exml.mb.showMess("JSON response received", 2000);
			 exml.parseJSON(cmlreq.responseText,title, latlon);
			}
		else {
                if (typeof ActiveXObject != "undefined") {
                    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                    xmlDoc.async = "false";
                    var response = cmlreq.responseText;
                    xmlDoc.validateOnParse = false;
                    xmlDoc.loadXML(response);
                    if (xmlDoc.parseError.errorCode) {
                        exml.mb.showMess(xmlDoc.parseError.reason + " line:" + xmlDoc.parseError.line);
                        if (cmlreq.responseText) {
                            alert(cmlreq.responseText);
                            }
                        }
                    else {
			exml.mb.showMess("GeoXML response received", 2000);
			var req={responseText:response,responseXML:xmlDoc};
			if(!isJSON) makeKMLlayer(req,title,latlon,nozoom);
			else exml.parseJSON(req.responseText,title, latlon);
                        }
                    }
                else {
                    if (cmlreq.responseXML) {
                        exml.mb.showMess("GeoXML response received", 2000);
			//var response = cmlreq.responseText;
                        makeKMLlayer(cmlreq,title,latlon,nozoom);
                        cmlrepeats = 0;
                        }
                    else {
 			      if (cmlreq.status == 200) {
                       	 	var resp = cmlreq.responseText;
                      		var sresp = resp.substring(0, 400);
                        	var isXML = resp.substring(0, 5);
                        	if (isXML == "<?xml" && sresp.indexOf("kml")!=-1) {
                                    exml.mb.showMess("GeoXML response received", 2000);
				    if(!isJSON) makeKMLlayer(resp,title,latlon,nozoom);
					else exml.parseJSON(resp.responseText,title, latlon);
                                    }
				else {
					exml.mb.showMess("File does not appear to be a valid GeoData"+resp,6000);
					}
                            	}
			}
                        }
                    }
                break;
            case 3:
                exml.mb.showMess("Receiving GeoXML...");
                break;
            case 2:
                exml.mb.showMess("Waiting for GeoXML",2000);
                break;
            case 1:
                exml.mb.showMess("Sent request",2000);
                break;
            }
        }

    if(top.setStatus)top.setStatus("sending settings");

    try {
        cmlreq.send(null);
        }
    catch (err) {
        if (cmlurl.substring(2, 3) == ":" && ! useLegacyLocalLoad) {
            useLegacyLocalLoad = true;
            loadKML(cmlurl);
            }
        }

}
function showBuilder(){
	if(top.widget){ popBuilder(); return; }
    if (top.standalone && typeof showModelessDialog != "undefined" ) {
        var set = showModelessDialog( 'tntmap-tabbed.hta',top,'resizable:yes;status:false;dialogWidth:733px;dialogHeight:343px;help:no;scroll:no' );
        	}
    else {
        window.open(codebase+"index.htm", "_blank", "status=yes,resizable=no,toolbar=0,height=343,width=733" );
        }
}

function toggleId(mid){
	var el = $(mid);
	if(el){
		if(el.style.display=="none"){ el.style.display =""; }
			else { el.style.display="none";}
		}
	}

function arrowToggle(){
	var img = $("arro");
	var mols = $("myoverlays");
	if(img.src.indexOf("minus")!=-1){ 
		img.src= codebase+"images/plus_sm.gif";
		mols.style.display="none";
		}
	else {
		img.src= codebase+"images/minus_sm.gif";
		mols.style.display="";
		}
	}

function moveToTop(al){
	var nl = [];
	var found = null;
	for(var k=0;k<layerList.length;k++){
		if(layerList[k].id != al){
			nl.push(layerList[k]);
			}
		else { 
			found = k; layerList[k].on = true;
			}
		}
	nl.push(layerList[found]);
	layerList = nl;
	writeWMSOverlays();
	}

function moveToBottom(al){
	var nl = [];
	var found = null;
	for(var k=0;k<layerList.length;k++){
		if(layerList[k].id!=al){
			nl.push(layerList[k]);
			}
		else { found = k; layerList[k].on = false; }
		}
	nl.unshift(layerList[found]);
	layerList = nl;
	writeWMSOverlays();
	}

var layerorder =[];
function initOverlays(){
	for(var i=0;i<layerList.length;i++){layerorder[i]=i;}
	}

function moveUp(){
	var n=activeRow;
	if(typeof n =="undefined")return;
	if (n == ovl.length-1){ return; }
	var temp = layerorder[n];
	layerorder[n] = layerorder[n+1];
	layerorder[n+1] = temp;
	setOrderTop(n);
	activeRow++;
	writeWMSOverlays();
	}

function moveDown(){
	var n = activeRow;
	if(typeof n =="undefined")return;
	if(n<1){ return; }
	var temp = layerorder[n-1];
	layerorder[n-1] = layerorder[n];
	layerorder[n] = temp;
	setOrderTop(n-1);
	activeRow--;
	writeWMSOverlays();
	}

function setOrderTop(n){
	var lo;
	var s = layerorder[n];
	if(layerList[n].on){ 
		for(i=s; i<ovl.length; i++){
			lo = layerorder[i];
			if(layerList[lo].on){
				wid = ovl[lo];
				if(wid)map.removeOverlay(wid);
				}
			}
		for(i=s;i<ovl.length;i++){
			lo = layerorder[i];
			wid = ovl[lo]; 
			if(layerList[lo].on){
				wid = ovl[lo];
				map.addOverlay(wid);
				}
			}
		}
	}
function makeBaseLayer(){
	if(typeof activeLayer == "undefined"){
		return; }
	if(activeLayer == ovl.length-1) { return; }
   	if(activeLayer == wmsbaselayer){
 		wmsbaselayer=null;
 		SetMapType(1);
 		}
 	else { 
		toggleOverlay(activeLayer,true);
		wmsbaselayer = parseInt(activeLayer);
		SetMapType(wmsbaselayer+3);
 	 	}
	}

var wmsbaselayer;
var activeLayer;
function selectRow(num){
	activeLayer=layerList[layerorder[num]].id;
	activeRow = num;
	for(var ol= (layerList.length-1); ol>-1; ol--) {
		var r = $("row"+ol);
		if(r){
			if(ol!=num){r.className='normRow';}
			else {r.className='selRow';}
			}
		}
	}
function gotoExtents(lid) {
	if(typeof activeLayer == "undefined")return;
	bounds = new GLatLngBounds(new GLatLng(-85,-180),new GLatLng(85,180));
	if(lid!=(layerList.length-1)) bounds = wms[lid*2].myExtents;  
	var ctr = bounds.getCenter();
    var z = map.getBoundsZoomLevel(bounds);
	map.setCenter(ctr,z);
	}

function closeLayers(e){
	hcontrols = setTimeout("hideControls()",500);
	}

var hcontrols;

function hideControls(){
	var lcb = $("lcb");
	if(lcb)lcb.style.display="";
	var lc2 = $("layerControls");
	if(lc2)lc2.style.display="none";
	}

function showControls(){
	if(hcontrols)clearTimeout(hcontrols);
	}
	
function initControls(){
	var lc2 = $("layerControls");
	lc2.style.display="block";
	var lcb = $("lcb");
	lcb.style.display="none";
	}


function writeWMSOverlays(){
	var oddrow=false;
	var hz=38;
	var htm ="";
	htm += "<span id=\"kml_layers\" style=\"display:none\"></span>";
	if(layerList && layerList.length){	
		htm += "<span style=\"font-weight:bold;color:SkyBlue\">Overlays</span><br/><div style=\"padding:0;margin:0;border:0;width:100%\">"
		for(var ol= (layerList.length-1); ol>-1; ol--) {
			var lo = layerorder[ol];
			if(lo!=wmsbaselayer) { 
			htm += "<div ";
			if(oddrow){
				htm += " class=\"oddrow\" ";
				oddrow=false; 
				}
			else {
				oddrow=true;
				}
			htm += ">";
		
			htm += "<div ";
			if(typeof activeRow!="undefined" && activeRow == ol){
				htm += "class=\"selRow\"";
				}
			else {
				htm += "class=\"normRow\"";
				}
			htm += "id=\"row"+ol+"\"";
			htm +=" onmousedown=\"selectRow("+ol+");\" style=\"width:100%\" >";
			htm += "<input type=\"checkbox\" id=\"ol"+layerList[lo].id+"\" ";
			if(layerList[lo].on){ htm+= "CHECKED "; }
			htm += " onclick=\"toggleOverlay('"+layerList[lo].id+"');\" ";
			htm += " />";
			htm += "<span id=\"ot"+layerList[lo].id+"\" ";
			if(layerList[lo].on) { htm +="class=\"layerOn\""; }
			else { htm += "class=\"layerOff\""; }
			htm += " >";	
			htm += ""+ layerList[lo].title+"</span>";
			htm += "</div>";
			}
		}
		htm += "<hr style=\"width:98%;padding:0;margin:0\" />";
		}
	var mt = map.getCurrentMapType();
	htm +="<span id=\"basemaptitle\" style=\"font-weight:bold;color:SkyBlue\">Base Maps</span><br/><span id=\"maptypelist\">";
	
	htm += "</span></div>";

	if(map.getMapTypes().length<4){
		htm += "<nobr><span id=\"builderbutton2\" onclick=\"showBuilder();\" style=\"cursor:pointer\"><img style=\"float:left\" src=\""+codebase+"images/star_vs.png\" />Use Layers from<br>Web Map Service</span></nobr>";

		}
	var wmso = $("wmsOverlays");
	if(wmso) { 
		wmso.innerHTML = htm;
		setTimeout("updateMapTypeList();",500);
		resizeControls();
		}
	}

function resizeControls(){
	var wmso = $("wmsOverlays");
	var lc = $("layerControls");
	var mo = $("map");
 	var mah = mo.offsetHeight;
	var logo = $('logo');
	if(logo){
		if(mo.offsetWidth < 400){
			logo.style.display="none";
			}
		else {
			logo.style.display='';
			}
		}
	var reqh = parseInt((layerList.length+6)*17.5); 
	if(layerList.length)reqh += 26;
	if(reqh > mah){ reqh = mah; }
	if(reqh<135 && layerList.length)reqh=135;
	if(lc){
		lc.style.height = reqh +"px";	
		lc.onmouseout = closeLayers;
		lc.onmouseover = showControls;
		}
	if(wmso){ wmso.style.height = reqh +"px"; }
	resizeKML();
	}
	
function clearAll() {
	hideAll();
	layerList=[];
	ovl = [];
	if(top.widget){
		widget.system("rm "+thisWidget+"/gmap.htm",null);
		com = "cp "+thisWidget+"/gmapstart.hta "+thisWidget+"/gmap.htm";
		widget.system(com,null);
		}
	writeWMSOverlays();
	}

function sortById(a,b){
	return a.id - b.id;
	}

function showTop(){
	var en=ovl.length-1;
	if(layerList && layerList.length != 0){
		layerList[en].on = true;
 		var wid = ovl[en];
		map.addOverlay(wid); 
		}
	writeWMSOverlays();
	}
	
function showAll(){
	var s;
	var st=0;
	var en=ovl.length;
	var wid;
	if(map.getCurrentMapType() != cmap3){st=1;}
	else {en--;}
	for(var i=st;i<en;i++){
		s = layerorder[i];
		if(layerList[s].on){
		 	wid = ovl[s];
			if(wid)map.removeOverlay(wid);
			}	
		}
	for(i=st;i<en;i++){
		s = layerorder[i];
		layerList[s].on = true;
 		wid = ovl[s];
		map.addOverlay(wid); 
		}
	writeWMSOverlays();
	}

var islocating;
function dolocate(url){
	if(islocating)clearTimeout(islocating);
	islocating = setTimeout("locate('"+url+"');",500);
	}
function ParseURL() {
	var loc = window.location.href;
	var q = loc.split("?");
	var s = q[1];
	var kmloverlay;
 	if(s){
		var comms = s.split("&");
		var x,y,z;
		for(i=0;i<comms.length;i++ ){
			 var c = comms[i];
 			while(c.indexOf("+")!=-1) c = c.replace("+"," ");
 			var duo = c.split("=");
 			if(duo[0].substring(0,1)=="?")duo[0] = duo[0].slice(1);
			var it = duo[0].toLowerCase();
 			switch(it){
				case "z" :
					z = parseFloat(duo[1]);
					break;
				case "lon":
				case "x":
				        x = parseFloat(duo[1]);
					break;
				case "lat":
				case "y" :
					 y= parseFloat(duo[1]);
					break;
				case "kml":
				case "addr":
				case "address":
					kmloverlay = duo[1];
					break;
				default:	 
				break;   
				}
			}
		if(typeof x!="undefined"||typeof z!="undefined"){
			map.setCenter(new GLatLng(y,x), z);
			return 1
			}
		if(typeof kmloverlay!="undefined" && kmloverlay !=""){
			var locating = dolocate(kmloverlay);
			}
		
	}
	return 0;
}

function showNormal(){
	var i;
	var s;
	var st=0;
	var en=ovl.length;
//	if(map.getCurrentMapType() != cmap3){st=1;}
//	else {en--;}
 	for(var i=st;i<en;i++){
		s = layerorder[i];
		wid = ovl[s];
		if(wid)map.removeOverlay(wid);
		}
	for(i=st;i<en;i++){
		s = layerorder[i];
		if(layerList[s].on == true){
 			wid = ovl[s];
			map.addOverlay(wid); 
			}
		}
	writeWMSOverlays();
	}

function hideAll(){
	var s;
	for(var i=0;i<ovl.length;i++){
		s = layerorder[i];
		if(layerList[s].on){
		 	wid = ovl[s];
			if(wid)map.removeOverlay(wid);
			layerList[s].on = false;
			}	
		}
	writeWMSOverlays();
}


var oldie;
function isOldIE(){
	if(!document.all){ oldie = false; return false; }
	var rv = 6;
	var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    	if (re.exec(navigator.userAgent) !== null){ rv = parseFloat( RegExp.$1 );}
	if(rv<7){ oldie = true;return true;}
	}
function getWinSize(){ //only used for IE6 maybe opera needs this too... seem to share common css problems (Opera=cludgy) 
	var s = {};
	if(top.dialogWidth){
		w = parseInt(dialogWidth);
		h = parseInt(dialogHeight);
		}
	 else if( typeof( window.innerWidth ) == 'number' ) { //Non-IE
    		w = window.innerWidth;
   		h = window.innerHeight;
		}
	 else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
   		 w = document.documentElement.clientWidth;
   		 h = document.documentElement.clientHeight; 
		}
	 else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
 		w = document.body.clientWidth;
    		h = document.body.clientHeight;
  		}
	s.w =w;s.h=h;
	return s;
	}

function resizeMap(){ 
    var mapobj = $("map");
	var zs = $("zs");
	var s = getWinSize(top);
	if(typeof s.h !="undefined"){	
		var sh = (s.h - 62)+"px";
		var sw = (s.w - 16)+"px";
		mapobj.style.height = sh;
		mapobj.style.width =  sw;
		if(zs) {
			zs.style.height = sh;
			zs.style.width = sw;
			}
		}
	resizeControls(); 	
	}

var throbbing;
var throbo = 100;
var throbber;
var up = false;

function cycle(){
	throbber = $('throbber');
	if(throbber.style.display != "none"){
		status = throbo;
		if(up){throbo += 5;}
		else {throbo -= 5;}
		if(throbo >= 100) { up=false; }
		if(throbo <= 0) { up=true;  }
		var mop = throbo/100;
		throbber.style.opacity = mop;
		throbber.style.KhtmlOpacity = mop;
		} 
	}
	
function throbCheck(){
	var tc=0;
	throbcounter += parseInt(wms.length/2,10) + 1;
	for(var w = 0;w<wms.length;w++){
			tc += wms[w].requestCount;
			}
	throbber = $('throbber');
	if(throbber) { 
		if(tc>throbcounter){  
			throbber.style.display=""; 
			throbber.title=" tiles="+tc+" tc="+throbcounter;
			}
		else { 
			throbber.style.display="none";
			throbcounter = 0;
			for(var n = 0;n<wms.length;n++){
				wms[n].requestCount = 0;
				}
			} 
		}
	}
 
	
function wheelZoom(a) { (a.detail || -a.wheelDelta) < 0 ? map.zoomIn(null,null,true) : map.zoomOut(null,true); }
var SEMI_MAJOR_AXIS = 6378137.0;
var ECCENTRICITY = 0.0818191913108718138;
var DEG2RAD=Math.PI/180.0;
var searchZoom = 12;
var maxZoom;

function dd2MercatorLon(lon) {
	return (lon*DEG2RAD)*SEMI_MAJOR_AXIS;
	}

function dd2MercatorLat(lat) {
	var rad = lat * DEG2RAD;
	var sinrad = Math.sin(rad);
	return (SEMI_MAJOR_AXIS * Math.log(Math.tan((rad + Math.PI/2) / 2) * Math.pow(((1 - ECCENTRICITY * sinrad) / (1 + ECCENTRICITY * sinrad)), (ECCENTRICITY/2))));
	}

 function CustomGetTileUrl(a,b,c) {
	if (typeof(this.myStyles)=="undefined") {
			this.myStyles=""; 
			}
	var lULP = new GPoint(a.x*256,(a.y+1)*256);
	var lLRP = new GPoint((a.x+1)*256,a.y*256);
	var lUL = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lULP,b,c);
	var lLR = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lLRP,b,c);
	var west = lUL.x;
	var east = lLR.x;
	var north = lUL.y;
	var south = lLR.y;
	var ge = east;
	var gw = west;
	var gs = south;
	var gn = north;
	if(gn < gs){ gs = gn; gn = south; }

	if(this.epsg != "EPSG:4326") {
		west = dd2MercatorLon(west);
		north = dd2MercatorLat(north);
		east = dd2MercatorLon(east);
		south = dd2MercatorLat(south);
		}
	var w = Math.abs(east - west);
	var h = Math.abs(north - south);
	var s = h/w;
	h = Math.round((256.0 * s) + 0.5);
	w = 256;
	var sud = south; 
	if(north < south){
		south = north; north = sud; 
		}
 
	if(typeof this.s != "undefined"){
		if(gs>(this.n) || ge < (this.w) || gn < (this.s) || gw > (this.e)  ){
			var retstr = codebase +"images/white.gif";
		 	if(this.myFormat=="image/jpeg" || this.myFormat == "JPEG" || this.myFormat == "JPG"){ return retstr; }
			return codebase +"images/blank.gif";
			}
		}
    var lBbox=west+","+south+","+east+","+north;
	var lSRS="EPSG:41001";
	if(typeof this.epsg != "undefined"){
    		lSRS=this.epsg;
		}
		
	var lURL=this.myBaseURL;
	if(typeof this.myVersion == "undefined"){ this.myVersion = "1.1.1"; }
	var ver = parseFloat(this.myVersion);
	lURL+="&SERVICE=WMS";
	if(this.myVersion !="1.0.0"){
		lURL+="&REQUEST=GetMap";
		}
	else {
		lURL+="&REQUEST=Map";
		}
	lURL+="&VERSION="+this.myVersion;
	if(this.myLayers) {
	lURL+="&LAYERS="+this.myLayers;
	lURL+="&STYLES="+this.myStyles; 
	}
	if(this.mySLD){
		lURL+="&SLD="+this.mySLD; 
		}
  	lURL+="&FORMAT="+this.myFormat;
 
	lURL+="&BGCOLOR=0xFFFFFF";
	lURL+="&TRANSPARENT=TRUE";
	if(this.myVersion == "1.1.1" || ver<1.3 ){
		lURL += "&SRS=" + lSRS;
		}
	else {
		lURL += "&CRS=" + lSRS;
		}
	lURL+="&BBOX="+lBbox;
	lURL+="&WIDTH="+w;
	lURL+="&HEIGHT="+h;
	this.requestCount++;
	return lURL;
	}
			 
				     // ====== Create a Client Geocoder ======
    var geo = new GClientGeocoder(); 

    // ====== Array for decoding the failure codes ======
    var reasons=[];
      reasons[G_GEO_SUCCESS]            = "Success";
      reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address";
      reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address";
      reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address";
      reasons[G_GEO_BAD_KEY]            = "Bad Key";
      reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries";

  function createInfoTipTabs(pt) {
	var b = map.getBounds();
	var sw = b.getSouthWest();
	var ne = b.getNorthEast();
	var w = sw.lng();
	var e = ne.lng();
	var n = ne.lat();
	var s = sw.lat();
	var ts = s;
	var tw = w;
	if(n<s) { s=n; n = ts; }
	if(e<w){ w=e; e = tw; }
	if(s<-90){ s=-90; }
	if(n>90){n=90;}
	if(e>180){ e=180; }
	if(w<-180){ w=-180; }

	var span_ew = Math.abs(e - w);
	var span_ns = Math.abs(n - s);
	var width;
	var height;
	if(span_ew < span_ns){
		width  = 1024*span_ew/span_ns;
		height = 1024;
		}
	else {
		width = 1024;
		height = 1024*span_ns/span_ew
		}
 
	var x = (pt.x - w) * width/span_ew;
	var y = (n - pt.y) * height/span_ns;
 
	var infoWindows = [];
	
	if(Requests.length<1){ return; }
	for(var r = 0;r<Requests.length;r++){
		var htm ="";
		var label = Requests[r].name;
		label = label.substring(0,10);
		htm += "<iframe style=\"width:325px;height:175px\" src=\""; 
		htm += Requests[r].url + "&BBOX="+w+","+s+","+e+","+n+"&X=";  
		htm +=  parseInt(x,10) +"&Y="+ parseInt(y,10) +"&WIDTH="+parseInt(width,10)+"&HEIGHT="+ parseInt(height,10);
		htm += "&ietype=.html";
		htm += "\" ></iframe>";
		var m = new GInfoWindowTab(label,htm);
		infoWindows.push(m);
		}
	return infoWindows;
	}

   function addInfoTipMarker(point){
	var arr = createInfoTipTabs(point);
	map.openInfoWindowTabsHtml(point, arr);  	 
	}

     function createTabbedMarker(point,html1,label1) {
        var marker = new GMarker(point);
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowTabsHtml([new GInfoWindowTab(label1,html1)]);
        });
        return marker;
      }
      
      function locate(nsearch) {
	if(!nsearch){
         	var sform = document.forms.sform;
 		if(sform){
			nsearch = sform.search.value;
			}
		}
	var p;	if(!nsearch){ return; }

	if(nsearch.indexOf("http")==0){ /* --- look for kml to load --- */
		var t = nsearch.split('/');
		loadKML(nsearch,t[t.length-1],false);
		return;
		}
        // ====== Perform the Geocoding ======        
        geo.getLocations(nsearch, function (result) { 
            // If that was successful
            if (result.Status.code == G_GEO_SUCCESS) {
              
              var mess = $("message");
	      if(mess){ mess.innerHTML = "Found " +result.Placemark.length +" results"; }
	      // Loop through the results, placing markers
              for (var i=0; i<result.Placemark.length; i++) {
                p = result.Placemark[i].Point.coordinates;
		var point = new GLatLng(p[1],p[0]);
		var marker = createTabbedMarker(point,"<span>"+result.Placemark[i].address+"</span>", "Address");	
                map.addOverlay(marker);
              }
		
	      var z = result.Placemark[0].AddressDetails.Accuracy;
	      if(z == 9) { z = 0; }
	      var zoom = 3 + 2 * parseInt(z,10);
	      map.setCenter(new GLatLng(p[1],p[0]),zoom);
		exml.mb.showMess("Search successful",3000);
              
            }
            // ====== Decode the error status ======
            else {
				var reason = "";
			    if(typeof reasons[result.Status.code]!= "undefined" ) {reason = reasons[result.Status.code]; }
				exml.mb.showMess("<center>Problem occured in search<br />Google Search Returned "+reason+" </center>", 3000);			 
               }
          }
        );

      } 
		  
		//preload mouseover Images
	function highlight(){
			var hl = $("hilite");
			hl.style.display = "";
			}
	function dim(){
			var hl = $("hilite");
			hl.style.display = "none";
			}
	function showHome() {
 		var bar = $("bg");
		bar.src = codebase+"images/gohome.png";
		  }
	function showInfo() {
 		var bar = $("bg");
		bar.src = codebase+"images/showinfo.png";
		  }
	function showGo() {
		var bar = $("bg");
		bar.src = codebase+"images/search.png";
		}

	function showNorm(){
		var bar = $("bg");
		var zbt = $("zbt");
		var zim = codebase+"images/dashed.png";
		if(mode == "zoombox"){
			bar.src = codebase+"images/static.png";
			zbt.src = codebase+"images/dasheda.png";
			}
		else if(mode=="measure"){
			bar.src = codebase+"images/gohome.png";
			zbt.src = zim;
			}
		else if(mode=="info"){
			bar.src = codebase+"images/showinfo.png";
			}
		else {
			bar.src = codebase+"images/static.png";
			zbt.src = zim;
			}
		}

 	var tb_left = 8;
	var tb_top = 8;

	function SetMapType(idx){
		var mt = map.getMapTypes();
		map.setMapType(mt[idx]);
 		if(idx<3){ 
			wmsbaselayer = null;
			}
		if(layerList.length)writeWMSOverlays();
		}
		
	function createToolbar(tbtop,tbleft,excludeZoombox,builder){ //innerHTML is faster than DOM methods in every browser currently.
		if(typeof builder != "undefined"){ includeBuilder = builder; }
		if(typeof tbtop == "undefined" ){tbtop = tb_top;}
		if(typeof tbleft == "undefined"){tbleft = tb_left;}

		var basez=300;
		
		
	 
		var tbc = "<div style=\"position:absolute;z-index:"+basez+";left:0px;top:0;width:100%;padding:0px;margin:0px\">\n";
		
				
		tbc += "<img onclick=\"showURL('http://www.microimages.com/tntserver/info.htm')\" id=\"logo\" style=\"position:absolute;z-index:"+(basez+12)+";top:2px;right:14px;\" src=\"" + codebase + "images/logosm.png\">";
		tbc += "<img onclick=\"showURL('http://www.microimages.com/tntserver/info.htm')\" id=\"throbber\" src=\""+codebase+"images/highlightsm.png\" style=\"position:absolute;z-index:"+(basez+30)+";top:6px;right:6px;cursor:pointer;cursor:hand;\" />";
		tbc += "<div title=\"Iconize\" class=\"closea\" style=\"position:absolute;left:5px;top:6px;height:14px;width:14px;font-size:14px;text-align:middle\" onmouseover=\"this.className='closeb'\" onmouseout=\"this.className='closea'\" onclick=\"this.className='closea';top.animateClose('viewer');\"><img style=\"height:14px;width:14px\" src=\"images/blank.gif\" /></div>";
		tbc += "<img id=\"hilite\" onmouseout=\"dim()\"  style=\"position:absolute;z-index:"+(basez)+";top:-8px;left:"+(tbleft+14)+"px;cursor:pointer;cursor:hand;behavior('"+codebase+"png.htc');display:none;\" onclick=\"showBuilder();\"  src=\""+codebase+"images/highlightsm.png\"/>";
		tbc += "<img title=\"Open TNTmap Builder\" onmouseout=\"dim()\" onmouseover=\"highlight(8)\" style=\"position:absolute;z-index:"+(basez+2)+";top:0px;left:"+(tbleft+15)+"px;cursor:pointer;cursor:hand;behavior('"+codebase+"png.htc');\" onclick=\"showBuilder();\"  src=\""+codebase+"images/star_sm.png\"/>";
		basez+=20; tbleft+=66; 
		tbc += "<div id=\"measures\" style=\"position:absolute;z-index:"+(basez+3)+";left:"+(tbleft+12)+"px;top:"+tbtop+"px;background:black;color:white;border: 3px outset;width:240px;height:24px;font-family:Verdana,Arial,sans-serif;font-size:10px;font-weight:bold;padding:3px;display:none\"></div>\n";

	 tbc += "<img id=\"bg\" style=\"position:absolute;z-index:"+(basez+5)+";top:"+tbtop+"px;left:"+tbleft+"px;\" src=\""+codebase+"images/static.png\">";
  		tbc += "<div style=\"position:absolute;z-index:"+(basez+10)+";left:"+tbleft+"px;top:6px;\">";
  		tbc += "<img title=\"Measure\" onclick=\"toggleMeasure()\" onmouseover=\"showHome()\" onmouseout=\"showNorm()\"  src=\""+codebase+"images/blank.gif\" style=\"cursor:pointer;cursor:hand;width:32px;height:30px\" />";
		if(Requests.length) {
			tbc += "<img title=\"Get feature info from Web Map Service\" onclick=\"toggleInfo()\" onmouseover=\"showInfo()\" onmouseout=\"showNorm()\" src=\""+codebase+"images/blank.gif\" style=\"width:32px;height:30px;cursor:pointer;cursor:hand;\" /> ";
			}
		else {
			tbc += "<img title=\"No Feature Information Available from Web Map Server\" src=\""+codebase+"images/blank.gif\" style=\"width:32px;height:30px;\" /> ";
			}
	 
  		tbc += "<div style=\"position:absolute;z-index:7540;left:48px;top:4px;\" >";
  		tbc += "<form style=\"display:inline\" name=\"sform\" onsubmit=\"locate($('search').value);return false;\" >";
		tbc += "<input id=\"search\" style=\"position:absolute;z-index:"+(basez+100)+";left:0px;top:4px;width:200px;height:16px;\" value=\"enter address\" type=\"text\" title=\"Input address(uses googlemaps geocoding)\" onchange=\"locate(this.value)\">";
		tbc += "</form>";
		tbc += "</div><div style=\"position:absolute;left:0;top:0\">";
		tbc += "<img onmouseover=\"showGo()\" onmouseout=\"showNorm()\" onclick=\"locate($('search').value)\" title=\"Go to address\" src=\""+codebase+"images/blank.gif\" style=\"position:absolute;z-index:"+(basez+20)+";top:8px;left:250px;width:30px;height:15px;cursor:pointer;cursor:hand;\" />";
tbc += "</div>";
		if(!excludeZoombox){
			tbc += "</div><img id=\"zbt\" title=\"Drag mouse across map to zoom\" style=\"position:absolute;z-index:"+(basez+25)+";top:8px;left:"+(tbleft+290)+"px;cursor:pointer;cursor:hand;behavior('"+codebase+"png.htc');\" onmouseover=\"showActiveZoom('zbt');\" onmouseout=\"showNorm();\" onclick=\"startBoxMode();\" src=\""+codebase+"images/dashed.png\" >";

			if(!top.widget){
				tbc += "<div style=\"position:absolute;z-index:"+(basez+28)+";top:8px;left:"+(tbleft+335)+"px;\"><img id=\"zbt\" title=\"Upload GeoXml File\" style=\"cursor:pointer;height:28px;width:28px;cursor:hand;behavior('"+codebase+"png.htc');\" onclick=\"getKML();\" src=\""+codebase+"images/geoxml.png\" ><span style=\"display:none\" id=\"kjsonsave\"><img  onclick=\"exml.saveJSON();\" style=\"cursor:height:28px;width:28px;pointer;cursor:hand;behavior('"+codebase+"png.htc');\" title=\"Save Overlays as KJSON\" src=\""+codebase+"images/kjson.png\" /><img  onclick=\"exml.clear();writeWMSOverlays()\" style=\"cursor:height:28px;width:28px;pointer;cursor:hand;behavior('"+codebase+"png.htc');\" title=\"Clear GeoXml Overlays\" src=\""+codebase+"images/cleargeoxml.png\" /></span></div>";
				}

			}
		else {
			if(!top.widget){
				tbc += "<div style=\"position:absolute;z-index:"+(basez+28)+";top:8px;left:"+(tbleft+300)+"px;\" ><img id=\"zbt\" title=\"Upload GeoXml File\" style=\"cursor:pointer;height:28px;width:28px;cursor:hand;behavior('"+codebase+"png.htc');\" onclick=\"getKML();\" src=\""+codebase+"images/geoxml.png\" ><span style=\"display:none\" id=\"kjsonsave\"><img  onclick=\"exml.saveJSON();\" style=\"cursor:height:28px;width:28px;pointer;cursor:hand;behavior('"+codebase+"png.htc');\" title=\"Save Overlays as KJSON\" src=\""+codebase+"images/kjson.png\" /><img  onclick=\"exml.clear();writeWMSOverlays()\" style=\"cursor:height:28px;width:28px;pointer;cursor:hand;behavior('"+codebase+"png.htc');\" title=\"Clear GeoXml Overlays\" src=\""+codebase+"images/cleargeoxml.png\" /></span></div>";
				}
			}
		if(top.widget) {
		tbc += "<div id=\"productname\" style=\"position:absolute;z-index:"+(basez+25)+";top:12px;left:"+(tbleft+355)+"px;font-size:10px;color:silver;font-weight:bold;white-space:nowrap;\" >Google Maps and<br /> WMS/WFS via TNTmap</div>";
		}
	
		
		tbc += "</div>";
		var tb = $('toolbar');
		tb.innerHTML = tbc; 
		
		showTop();
		}
	var setov;
	function showActiveZoom(mid){
		var b = $(mid);
		if(b){ b.src = codebase+"images/dasheda.png"; }
		}
	function setOvStyle(){
		var ov = $("map_overview");
	 
		if(ov && ov.firstChild) {
			ov.firstChild.style.borderStyle = "ridge";
			ov.firstChild.style.borderColor = "black";
			ov.firstChild.style.borderWidth = "4px";
			ov.firstChild.style.background = "black";
			}
	 	else {
			setov =	setTimeout(function(){ setOvStyle();},160);
			} 		
		}

function formatCoord(b){
	if (!b) {return "";}
	var t, t2;
	var d = Math.floor(b);
	var m = Math.floor( t = (b - d)*60 );
	var s = Math.floor( t2 = (t - m)*6000 );
	s = s/100.00;
	return  ("" + d + "\u00B0 " + m + "\u0027 " + s + "\u0022");
	}

function showCoords(pt){
	newcenter = pt;
	var nstr = 'S';
	var estr = 'W';
	if(pt.y>0){ nstr = 'N';}
	if(pt.x>0){ estr = 'E';}
	var nc = formatCoord(Math.abs(pt.y));
	var ec = formatCoord(Math.abs(pt.x));
	var cform = document.forms.coordset;
	if(cform){
			cform.myLat.value = ""+nstr +" "+nc;

			cform.myLon.value = estr +" "+ec;
		}
	}

function crossHairs(){
	var m = $("map");
	m.style.cursor = "crosshair";
	}

var points = [];
var markers = [];
var submarkers = [];
var mode = "";

var micon = new GIcon();
micon.image = "http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png";
micon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
micon.iconSize = new GSize(20, 20);
micon.shadowSize = new GSize(22, 20);
micon.iconAnchor = new GPoint(10, 10);
micon.infoWindowAnchor = new GPoint(6, 1);

var sicon = new GIcon();
sicon.image = "http://www.dyasdesigns.com/tntmap/images/small_circle.png";
sicon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
sicon.iconSize = new GSize(20, 20);
sicon.shadowSize = new GSize(22, 20);
sicon.iconAnchor = new GPoint(10, 10);
sicon.infoWindowAnchor = new GPoint(6, 1);

function removeNode(n){
	var newmarkers =[];
	for(var i=0;i<markers.length;i++){
		if(i==n) {
			map.removeOverlay(markers[i]);
			}
		else {
			markers[i].index = newmarkers.length;
			newmarkers.push(markers[i]);
			}
		}
	markers = newmarkers;
	connectTheDots();
	}

function insertMarker(n,mark){
	var newmarkers = [];
	for(var i=0;i<(n+1);i++){
		markers[i].index = newmarkers.length+1;
		newmarkers.push(markers[i]);
		}
	mark.index = newmarkers.length+1;
	newmarkers.push(mark);
	for(var j=(n+1);j<markers.length;j++){
	markers[j].index = newmarkers.length+1;
		newmarkers.push(markers[j]);
		}
	markers = newmarkers;
	}

function toggleMeasure(){
	GEvent.clearListeners(map,"click");
	if(mode=="measure"){
			var bar = $("bg");
			bar.src = codebase+"images/static.png";
			endMeasure();
			}
		else { 
			if(mode=="zoombox")endBoxMode();
			beginMeasure();
			}
		} 
var lines;

function toggleInfo(){
	GEvent.clearListeners(map,"click");
	if(mode=="zoombox")endBoxMode();
	if(mode == "info"){
		mode = "";
		var bar = $("bg");
		bar.src = codebase+"images/static.png";
		return;
		}
	mode = "info";
	$("map").firstChild.firstChild.style.cursor = "help"; 
	GEvent.addListener(map,"click", function (overlay, point){
			if(overlay){ return; }
			var pt = new GLatLng(point.y,point.x);
			addInfoTipMarker(pt);
			}
		); 
	}
 
var mline;
var pline = [];
 
function upgradeMarker(idx){
	var sm = submarkers[idx];
	var pt = sm.getLatLng();
	var sm = null;
	var nm = new GMarker(pt,{"icon":micon , draggable:true});
	GEvent.addDomListener(nm,"contextmenu",function(){ removeNode(this.index); })
	GEvent.addListener(nm,"dragend",function(){connectTheDots(this.index);});
	map.addOverlay(nm); 
 	insertMarker(idx,nm);
 	connectTheDots();
	}

var measgon;

function connectTheDots(idx){
	var num = 0;
	for(var i=num;i<pline.length;i++){
		if(pline[i])map.removeOverlay(pline[i]);
		}
	pline = [];
	for(var s=0;s<submarkers.length;s++){
		map.removeOverlay(submarkers[s]);
		}
	submarkers = [];

	var td=0;
	var lastpt = markers[num].getLatLng();
	markers[num].index = pline.length;

	if(measgon){ map.removeOverlay(measgon); }
	if(markers.length > 2){
		var points = Array(markers.length);
		for(var i = 0; i<markers.length; i++ ) { 
			points[i] = markers[i].getLatLng();
			}
		measgon = new GPolygon(points, "#f33f00", 1, 1, "#ff0000", 0.4, {clickable: false}); 
		measgon.fillColor = "#feef00";
		measgon.strokeColor =  "#ff0000";
		measgon.fillOpacity = 0.4;
		measgon.strokeWidth = 0;
		measgon.strokeWeight = 0;
		measgon.hilite = {"color":"#ffff00","fillOpacity" : 0.1};
		measgon.map = map;
		measgon.strokeOpacity = 0;
	 	measgon.onOver = function(){ this.realOpacity = this.fillOpacity; this.setFillOpacity(this.hilite.fillOpacity);};
  	 	measgon.onOut = function(){this.setFillOpacity(this.realOpacity);};
 
		map.addOverlay(measgon);
		}

	for(var i = num + 1; (i<markers.length); i++ ) { 
		var pt = markers[i].getLatLng();
		markers[i].index = pline.length+1;
		var line=[];
		line.push(lastpt);
		line.push(pt);
		td += pt.distanceFrom(lastpt);
		var seg = new GPolyline(line,"#ff00ff",1,.8);
		seg.title = "click to insert node";
        	seg.geoxml = exml;
        	seg.strokeColor = "#ff00ff";
        	seg.strokeWeight = 1;
		seg.strokeOpacity = .8;
		seg.hilite = "#ff0000";
		seg.map = map;
		seg.index = i - 1;
  		seg.onOver = function(){ this.realColor = this.strokeColor; this.setStrokeColor(this.hilite); };
		seg.onOut = function(){ this.setStrokeColor(this.realColor);};
		pline.push(seg)
		map.addOverlay(seg);

		var subpt = new GLatLng((lastpt.lat()+pt.lat())/2,(lastpt.lng()+pt.lng())/2);
		var mark = new GMarker(subpt,{"icon":sicon , draggable:true});
		mark.index = i -1;
		GEvent.addListener(mark,"dragend",function(){ upgradeMarker(this.index);});
		submarkers.push(mark);
		map.addOverlay(mark);
		lastpt = pt;
		}
	
	m = $("measures");
	var div = 1; 
	var units = "km";
	var squnits = "sq km";
	if(td > 2000){ div = 1000; }
	else { units="m"; squnits = "sq m"; }
	var dist = parseInt(td*1000,10)/(1000*div);

	if(!activeSystem){
	
		var htm="<p style=\"text-align:center;margin:1px;padding:0\">Distance "+dist+" "+units+"</p>";
		if(measgon){
			var basearea = measgon.getArea();
			var div = 1;
			if(basearea > 4000000){ div = 1000000; }
			var area = parseInt(basearea*100/div,10)/100;
			htm += "<p style=\"text-align:center;margin:1px;padding:0\">Area "+area+" "+squnits+"</p>";
			measgon.title = "Distance: "+dist+" "+units+" and  Area:"+area+" "+squnits;
			measgon.mess = htm;
			}
		m.innerHTML = htm;
		}
	else {
		dist /= 0.62;
		m.innerHTML="<p style=\"text-align:center;margin:1px;padding:0\">Distance "+dist+" miles</p>";
		if(measgon){ 
			var area = parseInt(measgon.getArea()*100/1000000,10)/384 ;
			htm += "<p style=\"text-align:center;margin:1px;padding:0\">Area "+area+" sq. miles.</p>";
			measgon.title = "Distance : "+dist+" miles and  Area:"+area+" sq miles";
			measgon.mess = htm;
			}
		}	
	}

 

function addPoint (overlay, point, idx){
	  	if(overlay){  
			if(overlay.title == "click to insert node"){
				insertionIndex = overlay.index;
				var v1 = overlay.getVertex(0);
				var v2 = overlay.getVertex(1);
				var pt = new GLatLng((v1.lat()+v2.lat())/2,(v1.lng()+v2.lng())/2);
				var mark = new GMarker(pt,{"icon":micon , draggable:true});
				GEvent.addListener(mark,"dragend",function(){connectTheDots(this.index);});
				GEvent.addDomListener(mark,"contextmenu",function(){ removeNode(this.index); })
				insertMarker(overlay.index,mark);
				map.addOverlay(mark);
				connectTheDots();
				slipDown();
				};
			return; 
			}
		var pt = new GLatLng(point.y,point.x);
		var startpt = new GMarker(pt,{"icon":micon , draggable:true});
		GEvent.addDomListener(startpt,"contextmenu",function(){ removeNode(this.index); })
		startpt.index = markers.length;
		markers.push(startpt);
	 	GEvent.addListener(startpt,"dragend",function(){connectTheDots(this.index);});
		map.addOverlay(startpt);
		connectTheDots(markers.length-1);
		slipDown();
		}

function beginMeasure(){
	slipDown();
	var m, p;
	mode = "measure";
	GEvent.addListener(map, "click", addPoint ); 
	}

function endMeasure(){
	mode = "";
	map.enableDragging();
	if(pline && pline.length > 0) {
		for(p=0;p<pline.length;p++){
			if(pline[p])map.removeOverlay(pline[p]); 
			}
		pline = [];	
		for(var m =0;m<markers.length;m++){
			var node = markers[m];
			if(node)map.removeOverlay(node);
			}
		markers = [];
		for(var s=0;s<submarkers.length;s++){
			map.removeOverlay(submarkers[s]);
			}
		submarkers = [];
		}
	if(measgon)map.removeOverlay(measgon)
	submarkers = [];
	GEvent.clearListeners(map,"click");
 	slipUp();
	}

function slipDown(){
	var m = $("measures");
	var t = parseInt(m.style.top,10);
	m.style.display="";
	if(t<36){
		m.style.top = (t+2) + "px";
		setTimeout(function(){slipDown();},10);
		}
 
	}
function slipUp(){
	var m = $("measures");
	var t = parseInt(m.style.top,10);
	if(t>7){
		m.style.top = (t-2) + "px";
		setTimeout(function(){slipUp();},10);
		}
	else {
		m.style.display ="none";
		}
	}


function getMouse(e){
	var l,t;
	if(!e&&window.event){ e=window.event; }
	if(window.event){
		l=parseInt(e.offsetX,10);
		t=parseInt(e.offsetY,10);
		}
	else{
		l=parseInt(e.layerX,10);
		t=parseInt(e.layerY,10);
		}
	var p={};
	p.x=l;
	p.y=t;
	return p;
	}

function endBoxMode(evt){
	if(!evt && window.event){evt = window.event;}
	if(window.event){
		event.cancelBubble=true; 
		event.returnValue=true;
		} 
	if(evt){
		if(evt.preventDefault){evt.preventDefault();}
		if(evt.stopPropogation){evt.stopPropogation();}
		}
	hideBox(false);
	mode="";
	showNorm();
	return false;
	}
function startBoxMode(){
	if(mode == "zoombox"){endBoxMode(); return; }
	var zs = $("zs");
	mode = "zoombox";
	showActiveZoom("zbutton");
	if(!zs.onmousemove){
		zs.onmousemove = moveBox;
		zs.onmousedown = startBox;
		zs.onmouseup = endBox;
		}
	zs.style.display="";
	$("toolbox").style.display="";
 
	}

function cancel(){ return true; }
function startBox(evt){
	if(!evt && window.event){evt = window.event;}
	if(window.event){
		event.cancelBubble=true; 
		event.returnValue=true;
		} 
	if(evt.preventDefault){evt.preventDefault();}
	if(evt.stopPropogation){evt.stopPropogation();}
	var zb = $("zbox");
	if(zb){ zb.style.visibility = "visible"; }
	pt = getMouse(evt);
	var m = $("map");
	var t = m.offsetTop;
	if(typeof t=="undefined"){
		t=0;
		}
	if(zb){
	 	zb.style.left = pt.x +"px";
 		zb.style.top = (pt.y + t)+"px";
		}
	return true;
	}
var pt;
function moveBox(evt){
	var m = getMouse(evt);
	var zb = $("zbox"); 
	var lr = map.fromContainerPixelToLatLng(new GPoint(m.x,m.y),map.getZoom());
	showCoords(lr);
	if(zb.style.visibility!="hidden"){
		zb.style.width = Math.abs(m.x - pt.x) +"px";
   		var mapobj = $("map");
		var mh = mapobj.offsetWidth;
		var mw = mapobj.offsetHeight;
		var sc = mw/mh;
		var sw = (m.x - pt.x)*sc;
		if(sw){
			zb.style.height = Math.abs(sw) +"px";
			}
	//	zb.style.height = Math.abs(m.y - pt.y) +"px";
		}
	}
function hideBox(keepscreen){
	var zb = $("zbox");
	if(zb){
	    zb.style.visibility = "hidden";
	    zb.style.width = "1px";
	    zb.style.height= "1px";
	    zb.style.fontHeight = "0px";
	    }

	if(!keepscreen){
 		$("zs").style.display="none";
		$("toolbox").style.display="none";
		}
	}

function endBox(evt){
	var m = getMouse(evt);
	var bounds = new GLatLngBounds();
	var ul = map.fromContainerPixelToLatLng(new GPoint(pt.x,pt.y),map.getZoom());
	bounds.extend(ul);
	var lr = map.fromContainerPixelToLatLng(new GPoint(m.x,m.y),map.getZoom());
	bounds.extend(lr);
	var c = map.fromContainerPixelToLatLng(new GPoint((pt.x+m.x)/2,(pt.y + m.y)/2),map.getZoom());
	map.setCenter(c,map.getBoundsZoomLevel(bounds));
	hideBox(true);
	}
	
var mbid;
function addMessageBox(bid){
	mbid = bid;
	}
function createZoomBox(mid,boxstyle,screenstyle,mappos){

	setInterval("throbCheck()",1000);
	if(!boxstyle) { 
		zbstyle = "background-color:black;opacity:0.3;filter:alpha(opacity=30);border:white dashed 2px;";
		}
	if(!screenstyle) {
		screenstyle ="background-color:black;opacity:0.3;filter:alpha(opacity=30);";
		}
	if(!mappos){
		var mo = $("map");
		var t = mo.offsetTop;
		mappos= "left:0px;top:"+t+"px;width:100%;height:100%;";
		}	
	var code = "<div id=\"zbox\" style=\"position:absolute;z-index:28000;left:0;top:0px;width:4px;height:4px;visibility:hidden;"+boxstyle+"\"></div>";
	code += "<div id=\"zs\" style=\"position:absolute;z-index:29000;"+mappos+"display:none;"+screenstyle+"\" ></div></div>";
	if(top.widget){
			code += "<div id=\"toolbox\" onmousedown=\"setTimeout('endBoxMode();',1000)\" style=\"position:absolute;top:42px;left:18px;width:72px;height:276px;z-index:29001;background:black;opacity:0.50;filter:alpha(opacity=50);border:3px outset silver;display:none\"></div>;"
	} else {
	code += "<div id=\"toolbox\" onmousedown=\"setTimeout('endBoxMode();',1000)\" style=\"position:absolute;top:42px;left:8px;width:65px;height:280px;z-index:29001;background:black;opacity:0.50;filter:alpha(opacity=50);border:3px outset silver;display:none\"></div>;"
	}	
 	var z = $(mid);
	if(z){
		z.innerHTML = code;
		}
	throbbing = setInterval("cycle()",50);
	GEvent.addDomListener(map.getContainer(), "DOMMouseScroll", wheelblock);
	map.getContainer().onmousewheel = wheelblock; 
	} 
  
 function wheelblock(e) {
		if (!e){ e = window.event }
		if (e.preventDefault){ e.preventDefault() }
		e.returnValue = false;
		}

function updateMapTypeList(){
	var mt = map.getCurrentMapType();
	var maptypes =  map.getMapTypes();
	var htm ="";
	var lt = $("layerTools");
	var bb = $("builderbutton2");
	var bmt = $("basemaptitle");
	var noshow="";
	var show="";
	if(maptypes.length>3) {
		for (var cm=3;cm <maptypes.length ;cm++){
			if(mt == maptypes[cm]){
				htm +="<input type=\"radio\" name=\"map_type\" ";
				if(mt == maptypes[cm]) { htm += "checked "; }
				htm += "onclick=\"SetMapType("+cm+");\" >"+maptypes[cm].getName()+"<br />\n";
				}
			}
		show ="";
		noshow="none";
		}
	else {
		show="none";
		noshow="";
		}
	if(lt)lt.style.display=show;
	if(bb)bb.style.display=noshow;
	htm +="<input type=\"radio\" name=\"map_type\" ";
	if(mt==maptypes[0]){ htm += "checked "; }
	htm += "onclick=\"SetMapType(0);\" >Map <br />";
	
	htm +="<input type=\"radio\" name=\"map_type\" ";
	if(mt==maptypes[1]) { htm += "checked "; }
	htm += "onclick=\"SetMapType(1);\" >Satellite <br />";

	htm +="<input type=\"radio\" name=\"map_type\" ";
	if(mt==maptypes[2]){ htm += "checked "; }
	htm += "onclick=\"SetMapType(2);\" >Terrain <br />\n";
	if($("maptypelist")) $("maptypelist").innerHTML = htm;

	}

