// mapFunctions.js

//     Date: 2007-Jun
//   Author: BDahms
// Revision: Modify isVisible() so overview map is hidden properly in Firefox
//           To handle IE7, generalize IE browser detection to just IE4 and versions higher than 4

// startup stuff when the map frame loads
var isIE = false;
var isNav = (navigator.appName.indexOf("Netscape")>=0);
var isNav4 = false;
var isNav5 = false;
var isIE4 = false;
var isIE5 = false;

var mapFrameWidth = 0;
var mapFrameHeight = 0;
var addBuffer = false;

var legendOn = false;
var helpOn = false;

var legwin_status = false;
var helpwin_status = false;
var legwin;
var helpwin;
var identifyOn = false;
var identifyReq = false;
var clickX;
var clickY;

var toggleId = false;
var panButtonArray = new Array(16);
//alert(navigator.appName+'\n'+navigator.appVersion);

var currentCandidateRequest = '';
var getReport = true;

var current_neighbourhood_id = '';
var neighbourhood_search = false;

// code to get the browser type and version
// assume IE3 is no longer used
if (isNav) {
	if (parseFloat(navigator.appVersion)<5) {
		isNav4 = true;
		isNav5 = false;
		theClient="Nav4";
	} else {
		isNav4 = false;
		isNav5 = true;
		theClient="Nav5 and up";
	}
} else {
	isIE=true;
	if ((navigator.appVersion.indexOf("MSIE 4")>0)) {
    		isIE4 = true;
		isIE5 = false;
		theClient="IE4";
    	} else {
		isIE4 = false;
		isIE5 = true;
		theClient="IE5 and up";
	}
}
//alert(theClient);

// get machine name
var hostname = document.location.host;

// set the URL used by some of the functions
var appPath = "/sitelocator/";

// it all starts here
function startUp(){
	init();
	getMap('startup');
}


function init() {
	//set parameters for mousedown events, identify operation
	if(isIE) document.onmousedown = mouseDown;

	if(isNav4){
		document.layers['mainmap'].captureEvents(Event.MOUSEDOWN);
		document.layers['mainmap'].onMouseDown = mouseDown;

		// top
		panButtonArray[0] = (mapFrameWidth/2)-20;
		panButtonArray[1] = 0;
		panButtonArray[2] = (mapFrameWidth/2)+20;
		panButtonArray[3] = 40;
		// bottom
		panButtonArray[4] = (mapFrameWidth/2)-20;
		panButtonArray[5] = mapFrameHeight-40;
		panButtonArray[6] = (mapFrameWidth/2)+20;
		panButtonArray[7] = mapFrameHeight;
		// left
		panButtonArray[8] = 0;
		panButtonArray[9] = (mapFrameHeight/2)-20;
		panButtonArray[10] = 40;
		panButtonArray[11] = (mapFrameWidth/2)+20;
		// right
		panButtonArray[12] = mapFrameWidth-40;
		panButtonArray[13] = (mapFrameHeight/2)-20;
		panButtonArray[14] = mapFrameWidth;
		panButtonArray[15] = (mapFrameHeight/2)+20;
	}
}

// get the mouse click x and y coordinates
function mouseDown(e) {
	var panClick = false;
	var dir = '';
	if ((isNav4 && e.which!=1)|| (isIE && event.button!=1)) return true
	if (isNav4) {

			clickx = e.pageX;
			clicky = e.pageY;
			var incr = 0;
			var dir = 'top';
			// order is left,top,right,bottom
			for(var i=0;i<4;i++){
				if((clickx >= panButtonArray[incr])&&(clicky >= panButtonArray[incr+1])&&(clickx <= panButtonArray[incr+2])&&(clicky <= panButtonArray[incr+3])){
					panClick = true
					if(incr == 4){
						dir = 'bottom';
					} else
					if(incr == 8){
						dir = 'left';
					} else
					if(incr == 12){
						dir = 'right';
					} 
				} 
				//alert('x: '+panButtonArray[incr]+' < '+clickx+' < '+panButtonArray[incr+2]+'\n y: '+panButtonArray[incr+1]+' < '+clicky+' < '+panButtonArray[incr+3]);
				incr = incr+4
				
			}
		}
	if ((isIE)||(isNav5)) {
			clickx = event.x;
			clicky = event.y;
		}
	//alert(clickx+','+clicky+' identifyOn: '+identifyOn+' toggleId: '+toggleId);
	if((identifyOn)&&(!toggleId)&&(!panClick)){
		if(clickx != ''){
			getIdentify(clickx,clicky);
		}
	}
	if(panClick){
		pan(dir);
	}
	toggleId = false;

}

// gets the URL of the mapimage and loads it into the mainmap/ovmap
// also opens the report popup window and gets the report 
function retrieveMapImage(){

  if(parent.aspFrame.errortext != null){
     if(parent.aspFrame.errortext != ''){
		if(parent.aspFrame.errortype == 1){
			parent.queryFrame.location =  "query.htm?start=true";
		}
		alert(parent.aspFrame.errortext);
	 }
  }
  if(parent.aspFrame.imgurl != null){
	if(parent.aspFrame.imgurl != ''){
		//alert('parent.aspFrame.imgurl is: '+parent.aspFrame.imgurl);
		if (isIE) {
			var content = '<input type="image" src="'+parent.aspFrame.imgurl+'" width="'+(mapFrameWidth-4)+'" height="'+(mapFrameHeight-4)+'" name="map" border="0" >';
		} else {
			var content = '<img src="'+parent.aspFrame.imgurl+'" width="'+(mapFrameWidth-4)+'" height="'+(mapFrameHeight-4)+'" border="0" >';
		}
		replaceLayerContent('mainmap',content);
	}
  }
   if(parent.aspFrame.ovimgurl != null){
	if(parent.aspFrame.ovimgurl != ''){
		//alert('parent.base.imgurl is: '+parent.base.imgurl);
		var content = '<img src="'+parent.aspFrame.ovimgurl+'" width="110" height="136" border="2">';
		//alert('content is: '+content);
		replaceLayerContent('ovmain',content);
	}
  }
  if(parent.aspFrame.reporturl != null){
	if(parent.aspFrame.reporturl != ''){
		window.open(parent.aspFrame.reporturl,"","width=700,height=350,scrollbars=yes,status=no,address=no,menubar=yes,toolbar=yes,resizable=yes")
	}
  }
   if(parent.aspFrame.identifyRoll != null){
	if(parent.aspFrame.identifyRoll != ''){
		selected_rollnum = parent.aspFrame.identifyRoll;
		var u =  "http://"+hostname+appPath+"buffer.asp?cmd=aspquery&roll="+parent.aspFrame.identifyRoll;
		parent.queryFrame.location = u;
	}
  }
  hideLayer("retrieving");
}

function resetCursor(){
	if (isNav4){
		document.layers["mainmap"].style.cursor = 'default';
	}else 
	if (isIE) {
		document.all("mainmap").style.cursor = 'default';
	}
}
// passes the click x y  coordinates to the server for an identify operation
function getIdentify(x,y){
	if(parent.queryFrame.roll_list != null){
		if(parent.queryFrame.roll_list != ""){
				var u = "http://"+hostname+appPath+"mapaction.asp?cmd=aspquery&action=identify&x="+x+"&y="+y;
				//alert(u);
				showLayer("retrieving");
				identifyReq = "true";
				parent.aspFrame.location = u;
		}
	}
}
// creates the DHTML layers - main map, ovmap, pan buttons
function createLayer(name, inleft, intop, width, height, content) {
	var layer;
	if (isNav4) {
	    document.writeln('<layer name="' + name + '" left=' + inleft + ' top=' + intop + ' width=' + width + ' height=' + height +  ' visibility="show">');
	    document.writeln(content);
	    document.writeln('</layer>');
	} else {
	    document.writeln('<div id="' + name + '" style="position:absolute; overflow:hidden; left:' + inleft + 'px; top:' + intop + 'px; width:' + width + 'px; height:' + height + 'px; z-index:1; visibility:visible;">');
	    document.writeln(content);
	    document.writeln('</div>');
	}
}
// replaces map/ovmap images when new map requested
function replaceLayerContent(name, content) {
	  if (isNav4) {
		    var layer = getLayer(name);
		    layer.document.open();
		    layer.document.writeln(content);
		    layer.document.close();
	  }  else if (isIE) {
		    var str = "document.all." + name + ".innerHTML = '" + content + "'";
			//alert(str);
		    eval(str);
	  } else if (isNav5){
			 var str = "document.getElementById('" + name + "').innerHTML = '" + content + "'";
			//alert(str);
		    eval(str);
	  }
}

// handler functions for menu buttons
function zoomOut(){
	if(!isVisible('retrieving')){
		getMap('zoomout');
	}
}
function zoomIn(){
	if(!isVisible('retrieving')){
		getMap('zoomin');
	}
}
function pan(direction){
	if(!isVisible('retrieving')){
		//alert('in pan function, direction is '+direction);
		if(identifyOn){ 
			identifyOn = false;
			toggleId = true;
		}
		getMap(direction);
		if(toggleId) identifyOn = true;
		//alert('in pan');
	}
}

// retrieves list of candidates based on query parameters selected in querytools.asp
function getCandidates(args){
	if(!isVisible('retrieving')){
		if(args != ''){
			var u = "http://"+hostname+appPath+"querycnd.asp?cmd=aspquery&"+args;
			currentCandidateRequest = u;
			parent.queryFrame.location = u;
		}
	}
}

function reloadCandidatePage(){
	if(currentCandidateRequest != ''){
		parent.queryFrame.location = currentCandidateRequest;
	}
}

// gets list of rollnumbers from querycnd.asp page, renders selections on map
function displayCandidates(){
	var whereclause = '';
	//alert(parent.queryFrame.roll_list);
	if(!isVisible('retrieving')){
		if (parent.queryFrame.roll_list != null){
			if(parent.queryFrame.roll_list != ''){
				var rollarray = parent.queryFrame.roll_list.split('_'); 
				if(!isIE){
				   whereclause = "ROLL_NUM%20=%20";
				}
				else {
				   whereclause = "ROLL_NUM = ";
				}
				
				//alert(whereclause);
				
				if(rollarray.length > 1){
					for(var i=0;i<rollarray.length-1;i++){
						if(!isIE){
							if(rollarray[i]!=''){
								whereclause += rollarray[i] + "%20OR%20ROLL_NUM%20=%20";
							}
						} else {
							if(rollarray[i]!=''){
								whereclause += rollarray[i] + " OR ROLL_NUM = ";
							}
						}
					}
					whereclause += rollarray[rollarray.length-1];
				} 
				else { 
					whereclause += rollarray[0];
				}
				//alert(whereclause);
				document.forms[0].args.value = whereclause;
				//document.forms[0].action="mapaction.asp?cmd=aspquery&action=selectparcels";
				//alert("action: " + document.forms[0].action + "\nargs value: " + document.forms[0].args.value);
				//alert("args value: " + document.forms[0].args.value);
				identifyOn = true;
				//alert('setting identifyOn to '+identifyOn);
				// change mouse cursor to crosshair for identify
				if (isIE) {
					document.all("mainmap").style.cursor = 'crosshair';
    			}
				document.forms[0].submit();
				showLayer('retrieving');
			}
		}
	}
}

// page scope var for storing current selected roll number 
var selected_rollnum = '';
// edit June 21/02
var selected_address = '';
var selected_id = '';
// retrieves the selected candidate and displays on map
function selectCandidate(rollnum,address,id){
	if(!isVisible('retrieving')){
		//alert(rollnum);
		//parent.queryFrame.location = "buffer.htm";
		selected_rollnum = rollnum;
		// edit June 21/02
		selected_address = escape(address);
		selected_id = id;

		identifyOn = false;
		identifyReq = false;
		if (isIE) {
			resetCursor();
		}
		// edit June 21/02
		var u = 'buffer.asp?cmd=aspquery&roll='+rollnum+'&address='+selected_address+'&id='+selected_id;
		//alert('selectCandidate URL is '+u);
		parent.queryFrame.location = u;
	}
}

function zoomToRegion(id,name){
	if(!isVisible('retrieving')){
		current_neighbourhood_id = id;
		var u = "bufferarea.asp?cmd=aspquery&id="+id+"&name="+name;
		parent.queryFrame.location = u;
		u = 'mapaction.asp?cmd=aspquery&action=zoomtoarea&areaid='+id;
		parent.aspFrame.location = u;
		showLayer('retrieving');
	}
}

function showCandidate(){
		var u = "http://"+hostname+appPath+"mapaction.asp?cmd=aspquery&action=single&roll="+selected_rollnum;
		//alert(u);
		if(!isVisible('retrieving')){
			parent.aspFrame.location = u;
			showLayer('retrieving');
		}
}

// closes popups when app exits
function closeWindows(){
	//alert('in closeWindows');
	if(legwin_status) legwin.close();
	if(helpwin_status) helpwin.close();
}

// popup window for legend
function showLegend(){
	var u = "http://"+hostname+appPath+"legend.htm";
	var xpos = 0;
	var ypos = 0;
	//alert(parent.titleFrame.legwin_status);
	if(!legwin_status){
		if ((isIE5) || (isNav5)) {
			ypos = screen.availHeight/9;
			xpos = screen.availWidth*0.8; 
			legwin = 	window.open(u,"legwindow","left="+xpos+",top="+ypos+",width=129,height=400,status=no,address=no,toolbar=no,menubar=no,resizable=no")
			legwin.focus();
		}
		else if ((isNav4)) {
			ypos = screen.height/9; 
			xpos = screen.width*0.8; 
			legwin = window.open(u,"legwindow","screenx="+xpos+",screeny="+ypos+",width=129,height=400,status=no,address=no,toolbar=no,menubar=no,resizable=no")
			legwin.focus();
		}
		legendOn = true;
		legwin_status = true;
	} else legwin.focus();
}

// popup window for help
function showHelp(){
	var u = "help.htm";
	var xpos = 0;
	var ypos = 0;
	if(!helpwin_status){
		if ((isIE5) || (isNav5)) {
			ypos = screen.availHeight/9;
			xpos = screen.availWidth*0.6; 
			helpwin =			window.open(u,"helpwindow","left="+xpos+",top="+ypos+",width=500,height=500,status=no,address=no,toolbar=no,menubar=no,resizable=yes,scrollbars=yes")
			helpwin.focus();
		}
		else if ((isNav4)) {
			ypos = screen.height/9; 
			xpos = screen.width*0.6; 
			helpwin =			window.open(u,"helpwindow","screenx="+xpos+",screeny="+ypos+",width=500,height=500,status=no,address=no,toolbar=no,menubar=no,resizable=yes,scrollbars=yes")
			helpwin.focus();
		}
		helpOn = true;
		helpwin_status = true;
	} else helpwin.focus();
}

function showCandidates(){
		var u = "http://"+hostname+appPath+"mapaction.asp?cmd=aspquery&action=selectparcels&";
		parent.aspFrame.location = u;
}

// replaces queryFrame with query.htm when new search button selected
function newSearch(){
	if(!isVisible('retrieving')){
		parent.queryFrame.location = "query.htm?start=true";
	}
}

// gets the report, generates the buffer if requested
function doBuffer(){
	var dembuff = parent.queryFrame.dBuffSize; 
	var busbuff = parent.queryFrame.bBuffSize; 
	var extraArgs = '';
	var layerInfo = '';
	var bufflimit = 99;
	var u = '';

// setup the pattern match and do it
	var chkResult1, chkResult2;
	var chkString = /[a-zA-Z]/;
	var chkResult1 = dembuff.match(chkString);
	var chkResult2 = busbuff.match(chkString);

	if(!isVisible('retrieving')){
		if(addBuffer){
			if(chkResult1 != null || chkResult2 != null) {
					alert('Please enter numeric values only.');
			} else {
				if((dembuff > bufflimit)||(dembuff < 0)){
					alert('A valid number between 0 and '+bufflimit+' must be entered.');
				} else if((busbuff > bufflimit)||(busbuff < 0)){
					alert('A valid number between 0 and '+bufflimit+' must be entered.');
				} else {
					if(dembuff == "") dembuff = 0;
					if(busbuff == "") busbuff = 0;
					extraArgs = '&d='+dembuff+'&b='+busbuff;
				}
			}
		} else {
			extraArgs = '&d=0&b=0';
		}

		showLayer("retrieving")
		//alert(parent.queryFrame.formb.chk1.checked+" "+parent.queryFrame.formb.chk2.checked+" "+parent.queryFrame.formb.chk3.checked+" "+parent.queryFrame.formb.chk4.checked+" "+parent.queryFrame.formb.chk5.checked);
		//alert(parent.queryFrame.formb.chk1.value+" "+parent.queryFrame.formb.chk2.value+" "+parent.queryFrame.formb.chk3.value+" "+parent.queryFrame.formb.chk4.value+" "+parent.queryFrame.formb.chk5.value);
		//alert(parent.queryFrame.lyr1+','+parent.queryFrame.lyr2+','+parent.queryFrame.lyr3);
		if(parent.queryFrame.lyr1){
			layerInfo += '&orth=show';
		} 
		if(parent.queryFrame.lyr2){
			layerInfo += '&emp=show';
		} 
		if (parent.queryFrame.lyr3){
			layerInfo += '&landuse=show';
		}
		if (parent.queryFrame.lyr4){
			layerInfo += '&util=show';
		}
		if(getReport){
			layerInfo += '&report=true';
		} else layerInfo += '&report=false';

		getReport = true;
		
		if((neighbourhood_search)&&(current_neighbourhood_id!='')){
			u = "http://"+hostname+appPath+"mapaction.asp?cmd=aspquery&action=buffer"+extraArgs+"&areaid="+current_neighbourhood_id+layerInfo+"&parcelreport=false";
		} else  
			u = "http://"+hostname+appPath+"mapaction.asp?cmd=aspquery&action=buffer"+extraArgs+"&id="+selected_id+"&roll="+selected_rollnum+"&address="+selected_address+layerInfo+"&parcelreport=true";

		//alert(u);
		parent.aspFrame.location = u;
	}
}

// new function added 08/02
function getMasterReport(reportType){
		var u = "http://"+hostname+appPath+"mapaction.asp?cmd=aspquery&action=masterreport&reportType="+reportType;
		parent.aspFrame.location = u;
}

// turns OV on/off
function toggleOV(){	
	//alert("toggleov() isVisible is " + isVisible('ovmain'));
	if(isVisible('ovmain')){
		hideLayer('ovmain');
	} else {
		showLayer('ovmain');
	}
}

// next set of functions are DHTML utility functions
function isVisible(name) {
	  var layer = getLayer(name);
	  //alert("isVisible() current visibility is " + layer.visibility);
	  if (isNav && layer.visibility == "show")
	  	return(true);
	  if (isNav && layer.visibility == "visible")  // for Mozilla Firefox
	  	return(true);
	  if (isIE && layer.visibility == "visible")
	  	return(true);
	  return(false);
}

// toggle layer to invisible
function hideLayer(name) {
  	var layer = getLayer(name);		
	//alert("hideLayer() current visibility is " + layer.visibility);
  	if (isNav4)
    		layer.visibility = "hide";
	else
   		layer.visibility = "hidden";
}

// toggle layer to visible
function showLayer(name) {	
  	var layer = getLayer(name);		
	//alert("showLayer() current visibility is " + layer.visibility);
  	if (isNav4)
    		layer.visibility = "show";
	else
   		layer.visibility = "visible";
}

// get the layer object called "name"
function getLayer(name) {
	  //alert("getLayer() name is " + name);
	  if (isNav4)
		return(document.layers[name]);
	  else if (isIE) {
		layer = eval('document.all.' + name + '.style');
		return(layer);
	  } else if (isNav) {
		var theElements = document.getElementsByTagName("DIV");
		var theObj;
		var j = -1;
		for (i=0;i<theElements.length;i++) {
			if (theElements[i].id==name) theObj = theElements[i].style;
		}
		return theObj
	  } else
		return(null);
}

//gets the map if a zoomin/zoomout/pan is requested
function getMap(arg){
	var action = arg;
	var uniqueNum = randNum();
	showLayer("retrieving");
	if (action == 'startup'){
		var u = "http://"+hostname+appPath+"mapaction.asp?cmd=aspquery&action=startup&w="+mapFrameWidth+"&h="+mapFrameHeight;
	} else {
		var u = "http://"+hostname+appPath+"mapaction.asp?cmd=aspquery&action="+action+"&r="+uniqueNum;
	}
	//alert(u);
	parent.aspFrame.location = u;
}

// expands the selected querytool - transition from query.htm to query.asp
function showTools(arg){
	if(arg != ''){
		var tempurl = "http://"+hostname+appPath+"querytools.asp?cmd=aspquery&qtype="+arg;
		parent.queryFrame.location.href = tempurl;
	}
}

// button image utilities
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function randNum () {
    var now = new Date();                                 
    var rand = now.getTime(); 
    if (rand < 0) rand = - rand; if (rand == 0) rand++;       
    return rand;                                          
    }







