/****************************************************************
* copyright 2000-2005 Geotechnologies, Inc, Inc all rights reserved. 
****************************************************************/

//****************** Initialization **********************

	var contents = "";
	var Coord = null;
	var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	var viewBox;
	var imageurl;
	var sz = 0.25;
	var viewx = 0;
	var viewy = 0;
	var viewscale = 1;
	var dataWin;
	var zoom=1.0;
	var userCoordsPoint;
	var scalebar = null;
	var dx = 0.0;
	var dy = 0.0;
	var lon;
	var lat;
	var tiledim;
	var imagetype;
	var imagename;


//*********************** Initialising Functions **********************

function getCoords(pixX, pixY) {

    if(svgroot) {
        var trans  = svgroot.getCurrentTranslate();
        var scale  = svgroot.getCurrentScale();
        var m      = viewBox.getTM();
        var p1     = svgroot.createSVGPoint();
        var p2;
        m = m.scale( 1/scale );
        m = m.translate(-trans.x, -trans.y);
        p1.x = pixX;
        p1.y = pixY;
        p2 = p1.matrixTransform(m);
        this.x = viewBox.X + p2.x;
        this.y = viewBox.Y + p2.y;
        }
}


function ViewBox(rootsvg) {

    if ( arguments.length > 0 ) {
        this.init(rootsvg);
    }
   }

ViewBox.prototype.init = function(rootsvg) {
//top.viewfr.isLoaded="true";
    var viewBox = rootsvg.getAttributeNS(null, "viewBox");
    var preserveAspectRatio = rootsvg.getAttributeNS(null, "preserveAspectRatio");
    
    if ( viewBox != "" ) {
      var vbox = viewBox.split(/\s*,\s*|\s+/);
     
    this.X = parseFloat(vbox[0]);
    this.Y = parseFloat(vbox[1]);
      this.x = 0;
      this.y = 0;
      this.width  = parseFloat( vbox[2] );
      this.height = parseFloat( vbox[3] );
            
    } else {
        this.x = 0;
        this.y = 0;
        this.width  = theInnerWidth;
        this.height = theInnerHeight;
    }
    this.setAspect(preserveAspectRatio);
}


ViewBox.prototype.setAspect = function(Aspect) {
    if ( Aspect ) {
        var splits = Aspect.split(/\s+/);
        var align  = splits[0];

        if ( align == "none" ) {
            this.alignX = "none";
            this.alignY = "none";
        } else {
            this.alignX = align.substring(1,4);
            this.alignY = align.substring(5,9);
        }

    } else {
        this.align  = "xMinYMin";
        this.alignX = "Min";
        this.alignY = "Min";
    }
}


ViewBox.prototype.getTM = function() {
        rootsvg = svgdoc.documentElement;
        var matrix  = svgdoc.documentElement.createSVGMatrix();
    var windowWidth = theInnerWidth;
    var windowHeight = theInnerHeight;

        var xr = this.width  / windowWidth;
        var yr = this.height / windowHeight;

    matrix = matrix.translate(this.x, this.y);
    

    if ( xr < yr ) {
        matrix = matrix.scale( yr );
    }
    else if ( xr > yr ) {
         matrix = matrix.scale( xr );
    }
    else {
        matrix = matrix.scale( xr );
    }
    return matrix;
}


function reSize() {
            
    theInnerHeight = top.viewfr.document.body.clientHeight;
    theInnerWidth = top.viewfr.document.body.clientWidth;
}

function point(ix, iy) 
{
	this.x = ix;
	this.y = iy;
}


	function resetView(x,y,s) {
		viewx = x;
		viewy = y;
		viewscale = s;
	}
//*********************** End of Initialising Functions **********************



	function on_load(e){
	
		svgdoc = e.target.ownerDocument;
		svgroot = svgdoc.getDocumentElement();
	   	reSize();

		// Set up our view box wrapper
      	viewBox = new ViewBox(svgdoc.documentElement);

		currentover = svgdoc.getElementById("canvas;");
		
		//set TitleLabel
	  	var title = top.viewfr.svgmap.src;
	  	//alert("title="+title);
	  	if (title.indexOf("&oldpath=")!= -1) title = title.substring(title.lastIndexOf("oldpath=")+8,title.lastIndexOf("/&"));
	  	if ((title.indexOf("&path=")!= -1)||(title.indexOf("?path=")!= -1)) title = title.substring(title.indexOf("path=")+5,title.lastIndexOf("."));
	  	if (title.indexOf("&image=")!= -1) {
	  		title = title.substring(title.lastIndexOf("&image=")+7);
	  		if (title.indexOf("&oldpath") != -1) title = title.substring(0,title.lastIndexOf("&oldpath"));
	  	}
	  	if (title.indexOf("queryUrl?")!= -1) title = title.substring(title.lastIndexOf("id=")+3,title.lastIndexOf("&"));

	  	else if (title.indexOf("/")!= -1) title = title.substring(title.lastIndexOf("/")+1,title.length);
	  	top.document.getElementById("TitleLabel").firstChild.nodeValue = title;

		//initialize sz parameters
		var vbox = (svgroot.getAttribute("viewBox")).split(' ');
		vboxW = parseFloat(vbox[2]);
		vboxH = parseFloat(vbox[3]);
		if (vboxW>vboxH) sz = (vboxW/40);
		else sz = vboxH/40;
		
		userCoordsPoint = new getCoords(vbox[0], vbox[1]);
		
		// initialize label text
		var data = svgdoc.createTextNode("");
		var text = svgdoc.createElement("text");
		text.setAttribute("transform","translate(0,0) scale(1.0)");
		text.setAttribute("style", "stroke:black;stroke-width:0.0001;fill:black;font-size:"+sz+";");
		text.setAttribute("id", "label");
		text.setAttribute("pointer-events","none");
		text.appendChild(data);
		svgroot.appendChild(text);
		if (svgdoc.getElementById("coord")) {
			coords = true;
		} else { 
			coords = false;
		}
	  	style = "stroke:black;stroke-width:0.0001;fill:black;fill-opacity:0";
		label =  svgdoc.getElementById("label");


		top.viewfr.isLoaded = true;

		// reset the zoom to original viewbox
		svgroot.currentTranslate.x = viewx;
		svgroot.currentTranslate.y = viewy;
		svgroot.currentScale = viewscale;
		
		if (top.toolfr.isLoaded) {
			top.toolfr.LayerLoad();
			Coord = top.toolfr.controldoc.getElementById("coord").firstChild;
		}//toolfr is loaded	
		insertScale();
	}
	
function insertScale() {
  if (top.viewfr.isLoaded) {
  	var coord = "utm";
	if (top.viewfr.svgroot.getAttribute("coord")) coord = top.viewfr.svgroot.getAttribute("coord");
	if (coord=="us48") {
		sc = "160900";
		top.viewfr.svgdoc.getElementById("utxt1").firstChild.nodeValue = "50mi";
		top.viewfr.svgdoc.getElementById("utxt2").firstChild.nodeValue = "100mi";	}
	if (coord.indexOf("utm")!= -1){
		sc = "16090";
		top.viewfr.svgdoc.getElementById("utxt1").firstChild.nodeValue = "5mi";
		top.viewfr.svgdoc.getElementById("utxt2").firstChild.nodeValue = "10mi";		
	}

	var trans = "translate("+(top.viewfr.viewBox.X+(top.viewfr.viewBox.width-top.viewfr.viewBox.width/15.0))+","+(top.viewfr.viewBox.Y+top.viewfr.viewBox.height/15.0)+") scale("+sc+")";
	top.viewfr.svgdoc.getElementById("scalebar").setAttribute("transform",trans);
  }
}

//******************* On Mouse Move Event *****************

function DoOnMouseMove(evt) {
	if (top.viewfr.isLoaded && top.toolfr.isLoaded) {
		//mousePoint.x = evt.screenX;
		//mousePoint.y = evt.screenY;
		if (Coord==null) Coord = top.toolfr.controldoc.getElementById("coord").firstChild;

		userCoordsPoint = new getCoords(evt.screenX, evt.screenY);
		label.setAttribute("transform","translate("+ userCoordsPoint.x+ "," + userCoordsPoint.y + ") scale(1.0)");
		if (vboxW>360) Coord.nodeValue = Math.round(userCoordsPoint.x) +","+(-Math.round(userCoordsPoint.y));
		else Coord.nodeValue = (Math.round(userCoordsPoint.x*1000.0)*0.001) +","+(-Math.round(userCoordsPoint.y*1000.0)*0.001);

		if (scalebar!=null) {
			scalebar.setAttribute("transform","translate("+ (userCoordsPoint.x-dx)+ "," + (userCoordsPoint.y+dy) + ") scale("+scalebar.getCTM().a+")");
		}
	}
}


//********** On Zoom Funtion ********************************

	function onZoom() {
		//top.viewfr.TypeSel="";
		label.style.setProperty("font-size",sz/svgroot.currentScale);
		//top.zoomview[top.loc] = svgroot.currentTranslate.x + ":" +svgroot.currentTranslate.y + ":" + svgroot.currentScale;
		//alert(svgroot.currentScale)
		//alert(top.viewfr.svgdoc.getElementById("scalebar").getCTM().e+","+top.viewfr.svgdoc.getElementById("scalebar").getCTM().f)
		
	}

//********************** Mouse Over Functions **********************
	// mouse_over

	function d(e) {
	  if (top.viewfr.isLoaded){
	  	var fill;
	  	var w;
		currentover = e.currentTarget;
		var id = currentover.id;
		if (currentover.getAttribute("name")) {
			var name = currentover.getAttribute("name");
			label.getFirstChild().setData(name);
		}
		else if (id!="") {
			label.getFirstChild().setData(id);
		}
					
		var svgstyle = currentover.getStyle();
		style = svgstyle.cssText;
		if (svgstyle.cssText=="") {
			parentstyle = currentover.parentNode.getStyle();
			fill = parentstyle.getPropertyValue('fill');
			w = parentstyle.getPropertyValue('stroke-width');
		}
		else {
			fill = svgstyle.getPropertyValue('fill');
			w = svgstyle.getPropertyValue('stroke-width');
		}
		if (fill=="none") {
			svgstyle.setProperty('stroke','red');
			svgstyle.setProperty('stroke-width',w*2);
		} 
		else 
		{
			if (fill=="red")  svgstyle.setProperty('fill','yellow');
			else svgstyle.setProperty('fill','red');
			svgstyle.setProperty('fill-opacity','0.25');
		}	
	  }
	}

	//mouse_out
	function e(e) {
	  if ((top.viewfr.isLoaded)&&(currentover)) {
			label.getFirstChild().setData("");
			if (currentover.id != "")  {
				currentover.setAttribute("style",style);
				currentover = null;	
			}
		}		
	}



//************* Changing the Viewfr *********************

function changeviewfr() {
	//alert("Success = " + xmlhttp.readyState + " type: " );

	if (xmlhttp.readyState==4) {

	 var content = xmlhttp.responseText;
	   if (content.indexOf("true")>=0) {
		top.viewfr.isLoaded = false;
		top.viewfr.svgmap.src = "Load?path="+path;
		var levels = path.split("/");
	  }
	  else {
		top.path = top.path.substring(0,top.path.lastIndexOf("/"));
		top.path = top.path.substring(0,top.path.lastIndexOf("/")+1);
	  }
	}
}

//*************************** On Mouse Click Fucntion *************************

function clicker(evt) {

    var newmap = true;
    var tgr = top.toolfr.controldoc.getElementById("tgr_line").firstChild.nextSibling.firstChild.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.getAttribute("visibility");
    var usgs = top.toolfr.controldoc.getElementById("usgs100k").firstChild.nextSibling.firstChild.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.getAttribute("visibility");
    var dem = top.toolfr.controldoc.getElementById("usgsdem250k").firstChild.nextSibling.firstChild.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.getAttribute("visibility");
    var nwi = top.toolfr.controldoc.getElementById("nwi").firstChild.nextSibling.firstChild.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.getAttribute("visibility");
    var doqq = top.toolfr.controldoc.getElementById("doqq").firstChild.nextSibling.firstChild.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.getAttribute("visibility");
    var drg = top.toolfr.controldoc.getElementById("drg").firstChild.nextSibling.firstChild.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.getAttribute("visibility");
    var cdwr = top.toolfr.controldoc.getElementById("cdwr-rivers").firstChild.nextSibling.firstChild.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.getAttribute("visibility");
    var relief3 = top.toolfr.controldoc.getElementById("relief3").firstChild.nextSibling.firstChild.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.getAttribute("visibility");
    var landsat = top.toolfr.controldoc.getElementById("landsat").firstChild.nextSibling.firstChild.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.getAttribute("visibility");
    
    if (top.viewfr.isLoaded) {
	    if (tgr=="visible") {
	    	var fips = currentover.id.substring(2,currentover.id.length);
	    	var url= "http://www2.census.gov/geo/tiger/tiger2004fe/CO/tgr"+fips+".zip";
	    	//alert(url);
	    	dataWin=window.open(url,"_self","width=2,height=2,left=500,top=500,scrollbars=no,toolbar=no, location=no, menubar=no, resizable=no,status=no");
	    }
	    else if (usgs=="visible") {
	    	var alpha = currentover.id.substring(0,1).toUpperCase();
	    	var url= "http://edcftp.cr.usgs.gov/pub/data/DLG/100K/"+alpha+"/"+currentover.id+"_CO/";
	    	//alert(url);
	    	if (dataWin!=null) dataWin.close();
	    	dataWin=window.open(url,"datawin","width=500,height=400,left=50,top=0,scrollbars=yes,toolbar=no, location=no, menubar=no, resizable=no,status=no");
	    	dataWin.focus();
	    }
	    else if (dem=="visible") {
	     	var name = currentover.getAttribute("name")
	    	var alpha = name.substring(0,1).toUpperCase();
	    	var url= "http://edcsgs9.cr.usgs.gov/pub/data/DEM/250/"+alpha+"/"+name+".gz";
	    	//alert(url);
	    	if (dataWin!=null) dataWin.close();
	    	dataWin=window.open(url,"_self","width=2,height=2,left=500,top=500,scrollbars=no,toolbar=no, location=no, menubar=no, resizable=no,status=no");
	    	dataWin.focus();
	    }
	    else if (doqq=="visible") {
			ShowImage("doqq");
			tiledim = 0.125;
	    }	
	    else if (drg=="visible") {
			ShowImage("drg");
			tiledim = 0.125;
	    }	
	    else if (relief3=="visible") {
			ShowImage("relief3");
			tiledim = 0.125;
	    }	
	    else if (landsat=="visible") {
			ShowImage("landsat");
			tiledim = 1.0;
	    }	    
	   	else if (nwi=="visible") {
			var name = currentover.getAttribute("name")
			name = name.substring(0,name.indexOf("-"));
			if ((name=="limon")||(name=="lamar")||(name=="leadville")){
				alert("Sorry, currently there is no nwi data available for "+name)
			}
			else {
				var url= "http://enterprise.nwi.fws.gov/wetlands/shapedata_nad83/";
		    	//no longer available var url= "http://www.nwi.fws.gov/shapedata/"+name+"/";
		    	//alert(url);
		    	if (dataWin!=null) dataWin.close();
				dataWin=window.open(url,"datawin","width=500,height=400,left=50,top=0,scrollbars=yes,toolbar=no, location=no, menubar=no, resizable=no,status=no");
		    	dataWin.focus();
	    	}
	    }
	    else if (cdwr=="visible") {
	    	var alpha = currentover.id.substring(0,1).toUpperCase();
	    	var url= "http://water.state.co.us/pubs/gis/riverd"+currentover.id+".zip";
	    	//alert(url);
	    	if (dataWin!=null) dataWin.close();
	    	dataWin=window.open(url,"_self","width=2,height=2,left=500,top=500,scrollbars=no,toolbar=no, location=no, menubar=no, resizable=no,status=no");
	    	dataWin.focus();
	    }
	    else {
		    if ((currentover)&&(evt.getButton()==0)&&(top.viewfr.isLoaded)) {// left mouse button
				if (currentover.parentNode.id.indexOf("COUNTIES")!=-1) {
					top.subregion = currentover.id;
					top.path = top.path+currentover.id+"/";
					path = top.path + currentover.id + ".svgz";
					//alert(top.path+"  "+path);
				}
				else if (currentover.parentNode.id=="plss") {
					top.subregion = "plss";
					top.path = top.path+"plss/";
					path = top.path + currentover.id + ".svgz";
					//alert(top.path+"  "+path);
				}
				
				else if (currentover.parentNode.id.indexOf("100k")!=-1) {
					top.subregion = currentover.parentNode.id;
					top.path = top.path+currentover.parentNode.id+"/";
					path = top.path + currentover.id + ".svgz";
					//alert(top.path+"  "+path);
				}
				
				else if (top.toolfr.controldoc.getElementById("usgs24k").firstChild.nextSibling.firstChild.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.getAttribute("visibility")=="visible") {
		  			// on single click do a map lookup in USGS dayabase
					if (dataWin!=null) dataWin.close();
					dataWin=window.open("MapLookup?index=" + currentover.id,"dataWindow2","width=500,height=400,left=50,top=0, scrollbars=yes, toolbar=no, location=np, menubar=no, resizable=yes, status=yes");
					dataWin.focus();
					newmap = false;
				} 
				else if (currentover.parentNode.id=="fedlanp020") {
						if (dataWin!=null) dataWin.close();
						//alert("queryData?database=Fips&table="+currentover.parentNode.id+"&id=" + currentover.id);
						dataWin=window.open("queryData?database=Fips&table="+currentover.parentNode.id+"&id=" + currentover.id,"dataWin","width=450,height=500,left=500,top=0,scrollbars=yes,toolbar=yes, location=no, menubar=yes,resizable=yes,status=yes");
						dataWin.focus();
						newmap = false;
				}
				else {
					top.path = top.path + currentover.id + "/";
					path = top.path + currentover.id + ".svgz";
				}
		        if (newmap) {
					//alert("Exists?path="+path);
				  	xmlhttp.Open("GET", "Exists?path="+path, false);
				  	xmlhttp.onreadystatechange=changeviewfr;
			   	  	xmlhttp.Send(null);
			    }
			}
		}
	}
}


	function ShowImage(type) {
		if (type=="doqq") type="doq";
		imagetype = type;
		imagename = currentover.id;
		name = currentover.id;
		//alert(name+"  "+type);
		lat = parseFloat(name.substring(0,2));
		if (type!="landsat") {
			var a = name.substring(5,6);
			//alert(lat+"  "+a);
			if(a=='B') lat = lat+0.125;
			else if (a=='C') lat = lat+0.25;
			else if (a=='D') lat = lat+0.375;
			else if (a=='E') lat = lat+0.5;
			else if (a=='F') lat = lat+0.625;
			else if (a=='G') lat = lat+0.75;
			else if (a=='H') lat = lat+0.875;	
		}									
		lon = -parseFloat(name.substring(2,5));
		if (type!="landsat") {
			var a = name.substring(6,7);
			//alert(lon+"  "+a);
			if(a=='2') lon = lon-0.125;
			else if (a=='3') lon = lon-0.25;
			else if (a=='4') lon = lon-0.375;
			else if (a=='5') lon = lon-0.5;
			else if (a=='6') lon = lon-0.625;
			else if (a=='7') lon = lon-0.75;
			else if (a=='8') lon = lon-0.875;
		}
		//alert(lat+":"+lon);
		var url = "LoadImage?type="+imagetype+"&lon="+lon+"&lat="+lat;
		if (type=="landsat") url = url + "&name="+currentover.getAttribute("name");
		//alert(url)
		if (dataWin!=null) dataWin.close();
		dataWin=window.open(url,"datawin","width=800,height=800,left=0,top=0,scrollbars=yes,toolbar=no, location=no, menubar=no, resizable=yes,status=yes");
		dataWin.focus();
	
	}
/*
	function ClickMap(evt) {
		//alert("ClickMap:"+lon+","+lat+"  "+imgtype+" "+evt.currentTarget.id)
		var dir = evt.currentTarget.id;
		var path = "";
		if (dir == "N") {
			lat = lat + 0.0625;
		}
		else if (dir == "NE") {
			lat = lat + 0.0625;
			lon = lon + 0.0625;
		}
		else if (dir == "E") {
			lon = lon + 0.0625;
		}
		else if (dir == "SE") {
			lat = lat - 0.0625;
			lon = lon + 0.0625;
		}
		else if (dir == "S") {
			lat = lat - 0.0625;
		}
		else if (dir == "SW") {
			lat = lat - 0.0625;
			lon = lon - 0.0625;
		}
		else if (dir == "W") {
			lon = lon - 0.0625;
		}
		else if (dir == "NW") {
			lat = lat + 0.0625;
			lon = lon - 0.0625;
		}
		if (dataWin!=null) dataWin.close();
		dataWin=window.open("LoadImage?type="+imagetype+"&lon="+lon+"&lat="+lat,"datawin","width=800,height=800,left=0,top=0,scrollbars=yes,toolbar=no, location=no, menubar=no, resizable=yes,status=yes");
		dataWin.focus();
	}
*/

	function queryData(evt) {
		var table = "";
		var database = "";
			table = evt.currentTarget.parentNode.id;
			//alert(table)
			if (table == "apt") database = "Airports";  // airports -Airports-apt,rmk,rwy
			else if (table == "censusppl") database = "maps"; // Dams  - maps-dams
			else if (table == "mining") database = "FIPS"; // Dams  - maps-dams
			else database="maps";
			if (database != "") {
				if (dataWin!=null) dataWin.close();
	//alert("queryData?database="+database+"&table="+table+"&id=" + currentover.id);
				dataWin=window.open("queryData?database="+database+"&table="+table+"&id=" + currentover.id,"dataWin","width=450,height=500,left=500,top=0,scrollbars=yes,toolbar=yes, location=no, menubar=yes,resizable=yes,status=yes");
				dataWin.focus();
			}
	}

 
	function startScale(evt){
		scalebar = evt.currentTarget;
		dx = userCoordsPoint.x - scalebar.getCTM().e;
		dy = userCoordsPoint.y - scalebar.getCTM().f;
	}
	
	function stopScale() {
		scalebar = null;
	}



