// 	Map Service Interface Code
//
// 	This code controls the interface to the ArcIMS map service
//	application for the Aerial Recon search tool. It utilizes the
//	XmlHttpRequest object (aka Ajax method) to dynamically 
//	update the map.
//	The Prototype.js and scriptaulous.js files are also required!!!
//
//	J. Christopher Jennings - last updated 1/24/06


// global map variables
var webServiceUrl = "/recon/reconservice.aspx"; // url to map web service
var mapAction; // can be: zoomin,zoomout,pan,select,getfeature
var minX;
var minY;
var maxX;
var maxY;
var minXC; // Cached minX value used when refreshing layers
var minYC; // Cached minY value used when refreshing layers
var maxXC; // Cached maxX value used when refreshing layers
var maxYC; // Cached maxY value used when refreshing layers
var mouseX = 0;
var mouseY = 0;
var mouseXC = 0; // initial cached value is 0
var mouseYC = 0; // initial cached value is 0
var activeLayer = 4; // set default active layer
var mapLayersVisible;
var mapStatus = "initial"; // if == refresh, then don't want to calculate x,y click coords
var iWidth = 260; // width of map image (used in fixed actions-zoom)
var iHeight = 260; // height of map image (used in fixed actions-zoom)
var loadingImage = '/recon/images/gis_spinner.gif';	

// page X,Y coordinates for mouse click
var pageClickX;
var pageClickY;


// ************ Begin Map GUI Code **************//
// This code controls the button rollovers, click events on the map, and layer visibility



// 
// SimpleSwap methods by Jehiah Czebotar
// http://jehiah.com/archive/simple-swap
// Version 1.1 - June 10, 2005
// Added method to onload event - Chris Jennings, June 2005
function SimpleSwap(el,which){
  el.src=el.getAttribute(which || "origsrc");
}

function SimpleSwapSetup(){
  var x = document.getElementsByTagName("img");
  for (var i=0;i<x.length;i++){
    var oversrc = x[i].getAttribute("oversrc");
    if (!oversrc) continue;
      
    // preload image
    // comment the next two lines to disable image pre-loading
    x[i].oversrc_img = new Image();
    x[i].oversrc_img.src=oversrc;
    // set event handlers
    x[i].onmouseover = new Function("SimpleSwap(this,'oversrc');");
    x[i].onmouseout = new Function("SimpleSwap(this);");
	//x[i].onclick = new Function("SimpleSwap(this,'oversrc');");
    // save original src
    x[i].setAttribute("origsrc",x[i].src);
  }
}

var PreSimpleSwapOnload =(window.onload)? window.onload : function(){};
window.onload = function(){
	PreSimpleSwapOnload(); 
	SimpleSwapSetup();
	initialMapLoad();
	updateVisibleLayers("initial");
	//updateServiceInfo();
	}


// Toggle the visibility of the layers in each folder as they're clicked.
function toggleLayerVis(targetId)
{
	if (document.getElementById)
	{
		target = $(targetId);
		if (target.style.display=="none") {
				new Effect.BlindDown(target);
				target.style.display="";
			} else if (target.style.height!="0px") {
				new Effect.BlindUp(target);
		}
	}
}

// Toggle the select drop-down menu for the layers
function toggle(targetId,state)
{
	if (document.getElementById)
	{
		target = $(targetId);
		if (state == 'on') {
			target.style.display="";
			} else {
			target.style.display="none";
		}
	}
}

// Activates the proper nav tool button and sets the mapAction variable
function activateTool(tool) {
	//$("activetool").innerHTML = 'Active Tool: ' + tool;
	if (tool == 'Zoom In') {
		mapAction = "zoomin";
		getMap();
	} else if (tool == 'Zoom Out') {
		mapAction = "zoomout";
		getMap();
	} else if (tool == 'PanEast') {
		mapAction = "paneast";
		getMap();
	} else if (tool == 'PanWest') {
		mapAction = "panwest";
		getMap();
	} else if (tool == 'PanNorth') {
		mapAction = "pannorth";
		getMap();
	} else if (tool == 'PanSouth') {
		mapAction = "pansouth";
		getMap();
	} else if (tool == 'Select Feature') {
		mapAction = "select";
	} else if (tool == 'Full Extent') {
		mapAction = "reset";
		initialMapLoad();
	}
}

// get page mouse coords on click and store in variables
document.onmousedown=detectMouseCoordinates;
function detectMouseCoordinates(e){
    var posx,posy;
    posx=0;
    posy=0;
    if(!e) var e=window.event;
    if(e.pageX||e.pageY){
          posx=e.pageX;
          posy=e.pageY;
		  //$("coords").innerHTML = 'X='+posx+' Y='+posy;
		  pageClickX = posx;
		  pageClickY = posy;
    }
    else if(e.clientX||e.clientY){
          posx = e.clientX + document.documentElement.scrollLeft;
          posy = e.clientY + document.documentElement.scrollTop;
		  //$("coords").innerHTML = 'X='+posx+' Y='+posy;
		  pageClickX = posx;
		  pageClickY = posy;
    }
}

// Calculate the X,Y coordinates of the clicked image in the form.
function calculateXY() {
	if (mapStatus != 'refresh') {
		var mapImageObject =  getElementPosition("mapimage");
		//alert('X=' + mapImageObject.left + ' Y=' + mapImageObject.top + ' Page x=' + pageClickX + ' Page y=' + pageClickY);
		// calculate actual x,y coords of map click
		mouseX = pageClickX - mapImageObject.left;
		mouseY = pageClickY - mapImageObject.top;
		//alert('X=' + mouseX + ' Y=' + mouseY);
		//return false;
	}
}

// Calculate the X,Y coordinates of a fixed action like zoom in/zoom out.
function calculateXYzoom() {
	if (mapStatus != 'refresh') {
		mouseX = iWidth/2;
		mouseY = iHeight/2;
	}
}

// Calculate the X,Y coordinates of a fixed action like zoom in/zoom out.
function calculateXYpan(direction) {
	if (mapStatus != 'refresh') {
		if (direction=='paneast') {
			mouseX = (iWidth/2) + (iWidth/4);
			mouseY = iHeight/2;
			//alert(mouseX + ", " + mouseY);
		} else if (direction=='panwest') {
			mouseX = iWidth/4;
			mouseY = iHeight/2;
		} else if (direction=='pannorth') {
			mouseX = iWidth/2;
			mouseY = iHeight/4;
		} else /* south */ {
			mouseX = iWidth/2;
			mouseY = (iHeight/2) + (iHeight/4);
		}
		// set mapAction back to pan for the webservice.
		mapAction = "pan";
	}
}


// Get the X,Y coordinates for the mapimage element
function getElementPosition(elemID) {
    var offsetTrail = $(elemID);
    var offsetLeft = 0;
    var offsetTop = 0;
    while (offsetTrail) {
        offsetLeft += offsetTrail.offsetLeft;
        offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.offsetParent;
    }
    if (navigator.userAgent.indexOf("Mac") != -1 && 
        typeof document.body.leftMargin != "undefined") {
        offsetLeft += document.body.leftMargin;
        offsetTop += document.body.topMargin;
    }
    return {left:offsetLeft, top:offsetTop};
}

// Update the active layer from the drop-down menu
function updateActiveLayer() {
	activeLayer = document.forms['mapform'].al.options[document.forms['mapform'].al.selectedIndex].value;
}

// Update the visible layers from the checkboxes
function updateVisibleLayers(status) {
	var layers = document.forms['mapform'].layers;
	var layersString = "";
	for (i=0; i<layers.length; ++i) {
		if (layers[i].checked) {
			layersString=layersString + '&l=' + layers[i].value;
		}
	}
	mapLayersVisible = layersString;
	
	if (status=='refresh'){
		mapStatus = "refresh";
		getMap();
	}
}
// *************  End Map GUI Code **************//




// ************ Begin Map Retrieval Code **************//
// At intial load, grab the default map image.
function initialMapLoad() {
	showStatus('on');
	var url;
	var pars;
	url = webServiceUrl;
	pars = "iheight=" + iHeight;
	pars += "&iwidth=" + iWidth;
	var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onSuccess: updateMap} );
}


// At intial load, get the service info.
// Not necessarily needed, but may be handy in future versions.
function updateServiceInfo() {
	mapAction = "serviceinfo";
	var url;
	url = webServiceUrl;
	var myAjax = new Ajax.Request( url, {method: 'get', onSuccess: updateMap} );
}


// Load status animation
function showStatus(status) {
	var statusImage = $('loadingImage');
	
	if (status=='on') {
		statusImage.src = loadingImage;
		statusImage.style.position = 'relative';
		statusImage.style.zIndex = '150';
		if (statusImage.style.display=="none") {
		statusImage.style.display="";
		}
	} else {
		if (statusImage.style.display=="") {
		statusImage.style.display="none";
		}
	}
}


// Name: getMap
// Purpose: to build an ArcXML request for a map image. Referenced by the form.
// Requires: Nothing
// Returns: Nothing
function getMap() {
	showStatus('on');
	
	// Calculate the x,y coords of mouse click within form image
	if (mapAction=='zoomin') {
		calculateXYzoom();
	} else if (mapAction=='zoomout') {
		calculateXYzoom();
	} else if (mapAction=='paneast') {
		calculateXYpan(mapAction);
	} else if (mapAction=='panwest') {
		calculateXYpan(mapAction);
	} else if (mapAction=='pannorth') {
		calculateXYpan(mapAction);
	} else if (mapAction=='pansouth') {
		calculateXYpan(mapAction);
	} else {
		calculateXY();
	}
	
	// Build map service url
	var url;
	var pars;
	url = webServiceUrl;
	pars = "action=" + mapAction;
	if (mapStatus == 'refresh') {
		pars += "&iheight=" + iHeight;
		pars += "&iwidth=" + iWidth;
		pars += "&minX=" + minXC;
		pars += "&minY=" + minYC;
		pars += "&maxX=" + maxXC;
		pars += "&maxY=" + maxYC;
	} else {
		pars += "&iheight=" + iHeight;
		pars += "&iwidth=" + iWidth;
		pars += "&minX=" + minX;
		pars += "&minY=" + minY;
		pars += "&maxX=" + maxX;
		pars += "&maxY=" + maxY;
		// Cache the envelope if simple map refresh or layer update is needed.
		minXC = minX;
		minYC = minY;
		maxXC = maxX;
		maxYC = maxY;
	}
	pars += "&xC=" + mouseXC;
	pars += "&yC=" + mouseYC;
	pars += "&x=" + mouseX;
	pars += "&y=" + mouseY;
	pars += "&al=" + activeLayer;
	pars += mapLayersVisible;
	// cache the x,y click coords
	mouseXC = mouseX;
	mouseYC = mouseY;
	
	// put URL into page for testing.
	//$('url').innerHTML = url + '?' + pars;
	
	// get the map and update page
	var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onSuccess: updateMap} ); 
	
	// prevent form from submitting
	mapStatus = "";	
	return false;
}

// Name: getFeature
// Purpose: to build an ArcXML request for a feature request
// Requires: Nothing
// Returns: Nothing
function getFeature() {
	// set map action to getfeature
	mapAction = "getfeature";
	
	// Build map service url
	var url;
	var pars;
	url = webServiceUrl;
	pars = "action=" + mapAction;
	pars += "&iheight=" + iHeight;
	pars += "&iwidth=" + iWidth;
	pars += "&minX=" + minX;
	pars += "&minY=" + minY;
	pars += "&maxX=" + maxX;
	pars += "&maxY=" + maxY;
	pars += "&x=" + mouseX;
	pars += "&y=" + mouseY;
	pars += "&al=" + activeLayer;
	// get the map and update page
	//alert(url);
	//$('url').innerHTML = url + '?' + pars;
	var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onSuccess: updateSearchForm} );
	mapAction = "select";
}

// Name: updateMap
// Purpose: to retrieve the map from the map service and update the web page.
// Requires: XML response from Ajax call
// Returns: Nothing
function updateMap(originalRequest) {
	showStatus('off');
	var mapElem = originalRequest.responseXML.getElementsByTagName("OUTPUT");
	var mapImageElem = $("mapimage");
	mapImageElem.setAttribute("src", mapElem[0].getAttribute("url"));
	
	// Assign the global envelope variables to the values returned by
	// the map service.
	var envelopeElem = originalRequest.responseXML.getElementsByTagName("ENVELOPE");
	if (mapStatus=='initial'){
		minX = envelopeElem[0].getAttribute("minx");
		minY = envelopeElem[0].getAttribute("miny");
		maxX = envelopeElem[0].getAttribute("maxx");
		maxY = envelopeElem[0].getAttribute("maxy");
		
		// Cache the envelope if simple map refresh or layer update is needed.
		minXC = minX;
		minYC = minY;
		maxXC = maxX;
		maxYC = maxY;
	} else if (mapStatus!='refresh') {
		minX = envelopeElem[0].getAttribute("minx");
		minY = envelopeElem[0].getAttribute("miny");
		maxX = envelopeElem[0].getAttribute("maxx");
		maxY = envelopeElem[0].getAttribute("maxy");
	}
	//$("envelope").innerHTML = 'minX =' + minX + ' minY =' + minY + ' maxX =' + maxX + ' maxY =' + maxY;
	//$("envelopecache").innerHTML = 'minXC =' + minXC + ' minYC =' + minYC + ' maxXC =' + maxXC + ' maxYC =' + maxYC;

	// if selecting feature call the getFeature method
	if (mapAction=='select') {
		getFeature();
	}
	
	//Update the legend
	updateLegend(originalRequest);
}

// Name: updateLegend
// Purpose: to retrieve the legend from the map service and update the web page.
// Requires: Nothing
// Returns: Nothing
function updateLegend(originalRequest) {
	var legendElem = originalRequest.responseXML.getElementsByTagName("LEGEND");
	var mapLegendElem = $("mapLegend");
	mapLegendElem.setAttribute("src",legendElem[0].getAttribute("url"));
}


// Name: updateSearchForm
// Purpose: to parse the feature response XML and update the search form.
// Requires: XML response from Ajax call
// Returns: Nothing
function updateSearchForm(originalRequest) {
	var fieldsElem = originalRequest.responseXML.getElementsByTagName("FIELDS")[0];
	var poiAttr = fieldsElem.getAttribute("ILRDSSgis.ILRDSS.RECON_POI_Pt.POI");
	var streamAttr = fieldsElem.getAttribute("ILRDSSgis.ILRDSS.RECON_POI_Pt.STR_NAME");
	var videoAttr = fieldsElem.getAttribute("ILRDSSgis.ILRDSS.RECON_POI_Pt.VIDEO");
	$("searchresults").innerHTML = '<strong>Point of Interest:</strong> ' + streamAttr + ' #' + poiAttr + '.';
	
	var videoURL = 'mms://ilrdss.isws.illinois.edu/AerialRecon/' + videoAttr + '.wmv'
	var openVideoURL = $("videolink");
	openVideoURL.setAttribute("href",videoURL);
	
	// show the video div container
	var videoDiv = $("section-video");
	if (videoDiv.style.display=="none") {
		videoDiv.style.display="";
		}
	
	var loadVideoURL = '<OBJECT ID="WMP7" CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" width="360" height="345">';
	loadVideoURL += '<PARAM id="video" NAME="URL" VALUE="';
	loadVideoURL += videoURL;
	loadVideoURL += '">';
	loadVideoURL += '</OBJECT>';
	$("videocontainer").innerHTML = loadVideoURL;
}

// Name: playFullVideo
// Purpose: Loads and plays full length aerial recon video.
// Requires: Nothing
// Returns: Nothing
function playFullVideo() {
	var videoName = document.fullvideoform.fullvideomenu.value;
	var areaTitle = document.fullvideoform.fullvideomenu.title;
	var videoURL = 'mms://ilrdss.isws.illinois.edu/AerialRecon/full_length/' + videoName + '.wmv'
	$("searchresults").innerHTML = '<strong>Full-Length Video:</strong> ' + videoName;
	
	var openVideoURL = $("videolink");
	openVideoURL.setAttribute("href",videoURL);
	
	// show the video div container
	var videoDiv = $("section-video");
	if (videoDiv.style.display=="none") {
		videoDiv.style.display="";
		}
	
	var loadVideoURL = '<OBJECT ID="WMP7" CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" width="360" height="345">';
	loadVideoURL += '<PARAM id="video" NAME="URL" VALUE="';
	loadVideoURL += videoURL;
	loadVideoURL += '">';
	loadVideoURL += '</OBJECT>';
	$("videocontainer").innerHTML = loadVideoURL;
	
	return false;
}
// ************ End Map Retrieval Code **************//