/*
	Map configuration and handling for UNEP OSDS
	Prepared by Hugo Ahlenius
	http://nordpil.com
	2011
*/
	
// {{{ GENERAL TOOL-LIKE SNIPPETS
function oc(a)
{
	// This function is from http://snook.ca/archives/javascript/testing_for_a_v
	// It can be used for if statements on arrays
	var o = {};
	for(var i=0;i<a.length;i++)
	{
	o[a[i]]='';
	}
	return o;
}
function clone(s) {
	for(p in s) {
		this[p] = (typeof(s[p]) == 'object')? new clone(s[p]) : s[p];
	}
}
// }}}
dojo.registerModulePath("tmpdir","./tmpdir");
dojo.require("esri.map");
dojo.require("dijit._base.place");
dojo.require("esri.toolbars.navigation");
dojo.require("esri.toolbars.draw");
dojo.require("dijit.form.Button");
dojo.require("dijit.Toolbar");
dojo.require("esri.dijit.OverviewMap");
dojo.require("esri.tasks.identify");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.layout.AccordionContainer");
dojo.require("esri.dijit.Legend");
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("tmpdir.CheckBoxTree");
dojo.require("dijit.Tree");
dojo.require("esri.InfoWindowBase");
esriConfig.defaults.map.slider = { left:"20px", top:"20px", width:null, height:"150px" };
var myMap, lyrBasemap, lyrGeodata, lyrOv, imagep, navToolbar, layersLoaded, loading, overviewMapDijit, geoLegend, drawToolbar, lyrGeodataLyr, activeCurr;
var hyperLayers = [];
var refLayers = [];
activeCurr = -1;
var curTool = 'zoomin';

// For layers that highlight search results
var searchGfxLayer = new esri.layers.GraphicsLayer();
searchGfxLayer.id = 'search';
var symSearchPoint = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, 7, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255,0,255]), 2), new dojo.Color([255,0,0]));
var symSearchPoly = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255,0,0]), 2), new dojo.Color([255,255,0,0.5]));
var symSearchPolyLine = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255,255,0,0.5]),3);

// Function hide the throbber/loader {{{
var hideLoader = function(){
    dojo.fadeOut({
        node:"preloader",
        onEnd: function(){
            dojo.style("preloader", "display", "none");
        }
    }).play();
}
dojo.addOnLoad(function(){
    hideLoader();
});
// }}}


// For layers that highlight AOI box
var aoiGfxLayer = new esri.layers.GraphicsLayer();
aoiGfxLayer.id = 'aoi';
var symAoiGrayBox = new esri.symbol.SimpleFillSymbol(
	esri.symbol.SimpleFillSymbol.STYLE_SOLID,
	new esri.symbol.SimpleLineSymbol(
	esri.symbol.SimpleLineSymbol.STYLE_NULL,
	new dojo.Color([200,0,0]), 2
	),
	new dojo.Color([0,0,0,0.1])
);
var symAoiHighlight = new esri.symbol.SimpleFillSymbol(
	esri.symbol.SimpleFillSymbol.STYLE_SOLID,
	new esri.symbol.SimpleLineSymbol(
		esri.symbol.SimpleLineSymbol.STYLE_DASHDOT,
		new dojo.Color([200,0,0]), 2
	),
	new dojo.Color([200,80,80,0.05])
);

function clearSearch() {
	myMap.infoWindow.hide();
	myMap.getLayer('search').clear();
}

// {{{ VIEW/PROJECTION STUFF
var thisView = 'geographic', maxExtent, startExtent, thisProj, thisBase;
if (document.location.href.match('arctic')) {
	document.cookie = 'cView=arctic_laea; expires=Fri, 3 Aug 2051 20:47:11 UTC; path=' + document.location.href.replace(/http:..[a-z.]+(\/.*\/)($|\?.*)/,'$1')
	document.location.href = document.location.href.replace(/\?.*/,'')
}
if (document.location.href.match('world')) {
	document.cookie = 'cView=geographic; expires=Fri, 3 Aug 2051 20:47:11 UTC; path=' + document.location.href.replace(/http:..[a-z.]+(\/.*\/)($|\?.*)/,'$1')
	document.location.href = document.location.href.replace(/\?.*/,'')
}
if (document.cookie.match(/cView/)) {
	thisView = document.cookie.replace(/.*cView=([a-z_]+)($|;.*)/,'$1');
}
if (document.cookie.match(new RegExp('pane' + thisView))) {
	// This brings up the pane that has been stored in the cookie
	paneInitial = document.cookie.replace(new RegExp('.*pane' + thisView +'=(.*?)($|;.*)'),'$1');
	dojo.addOnLoad(function(){if (dijit.byId(paneInitial)) {dijit.byId('leftAccordion').selectChild(paneInitial);}});
}
if (document.cookie.match(new RegExp('tool' + thisView))) {
	var thisTool = document.cookie.replace(new RegExp('.*tool' + thisView +'=(.*?)($|;.*)'),'$1');
}
var aoiNorth, aoiSouth, aoiEast, aoiWest;
switch (thisView) {
	case 'geographic':
		thisBase = 'http://maps.continentalshelf.org/ArcGIS/rest/services/shelfdatashop_bg_wgs84/MapServer';
		thisProj =  new esri.SpatialReference({wkid:4326});
		maxExtent = new esri.geometry.Extent(-180,-90,180,90, thisProj);
		// startExtent = new esri.geometry.Extent(-83,-74.5,19.72,57.4, thisProj);
		startExtent = new esri.geometry.Extent(-180,-90,180,90, thisProj);
		thisOV = 'http://maps.continentalshelf.org/ArcGIS/rest/services/ov_wgs84/MapServer';
		ovCutoff = 0.18;
		aoiNorth = 90;
		aoiSouth = -90;
		aoiEast = 180;
		aoiWest = -180;
		break;
	case 'arctic_laea':
		thisBase = 'http://maps.continentalshelf.org/ArcGIS/rest/services/shelfdatashop_bg_laea/MapServer';
		thisProj =  new esri.SpatialReference({ wkt:"PROJCS[\"Arctic LAEA greenwich\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Lambert_Azimuthal_Equal_Area\"],PARAMETER[\"False_Easting\",0.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",0.0],PARAMETER[\"Latitude_Of_Origin\",90.0],UNIT[\"Meter\",1.0]]" });
		thisProj =  new esri.SpatialReference({wkid:102017});
		maxExtent = new esri.geometry.Extent(-3000000,-3000000,3000000,3000000, thisProj);
		startExtent = new esri.geometry.Extent(-2200000,-2200000,2200000,2200000, thisProj);
		thisOV = 'http://maps.continentalshelf.org/ArcGIS/rest/services/ov_laea/MapServer';
		ovCutoff = 0.4;
		aoiNorth = 2000000;
		aoiSouth = -2000000;
		aoiEast = 2000000;
		aoiWest = -2000000;
		break;
}
//}}}
//{{{ INITIALIZE THE VIEW FROM COOKIE
	if (document.cookie.replace(new RegExp('.*ext' + thisView + '.*'),'yes') == 'yes') {
		startExtent.xmax = parseFloat(document.cookie.replace(new RegExp('.*ext' + thisView + '=([0-9,.-]+).*'),"$1").split(',')[0]);
		startExtent.ymax = parseFloat(document.cookie.replace(new RegExp('.*ext' + thisView + '=([0-9,.-]+).*'),"$1").split(',')[1]);
		startExtent.xmin = parseFloat(document.cookie.replace(new RegExp('.*ext' + thisView + '=([0-9,.-]+).*'),"$1").split(',')[2]);
		startExtent.ymin = parseFloat(document.cookie.replace(new RegExp('.*ext' + thisView + '=([0-9,.-]+).*'),"$1").split(',')[3]);
	}
	if (document.cookie.replace(new RegExp('.*aoi' + thisView + '.*'),'yes') == 'yes') {
		aoiNorth = document.cookie.replace(new RegExp('.*aoi' + thisView + '=([0-9,.-]+).*'),"$1").split(',')[0];
		aoiEast = document.cookie.replace(new RegExp('.*aoi' + thisView + '=([0-9,.-]+).*'),"$1").split(',')[1];
		aoiSouth = document.cookie.replace(new RegExp('.*aoi' + thisView + '=([0-9,.-]+).*'),"$1").split(',')[2];
		aoiWest = document.cookie.replace(new RegExp('.*aoi' + thisView + '=([0-9,.-]+).*'),"$1").split(',')[3];
	}
//}}}
var identifyTask, identifyParams, symbol;
var currIdResults;

function beautLink(inLink, identifier) {
	var outLink = identifier;
	if (identifier.length > 12) {
		// outLink = '...' + outLink.slice(-8)
		// outLink = inLink.split('/')[2]
		outLink = 'click here';
	}
	return outLink;
}
function init() {
	layersLoaded = 0;
	loading = dojo.byId("loadingImg");  //loading image. id
	myMap = new esri.Map("mapDiv", {extent:startExtent, nav:false, logo:false, fitExtent:true, wrapAroudn180:true});
	myMap.showPanArrows();
	lyrOv = new esri.layers.ArcGISDynamicMapServiceLayer
		(thisOV);
	dojo.connect(lyrOv,"onUpdateEnd", hideLoading);
	lyrBasemap = new esri.layers.ArcGISTiledMapServiceLayer
		(thisBase);
	myMap.addLayer(lyrBasemap,1);
	myMap.addLayer(lyrOv,0);
	lyrGeodata = new esri.layers.ArcGISDynamicMapServiceLayer
		("http://maps.continentalshelf.org/ArcGIS/rest/services/shelfdatashop_geodata_wgs84/MapServer");
	if (lyrGeodata.loaded) {
		buildLayerList(lyrGeodata);
		updateActiveLayersList();
	}
	else {
		dojo.connect(lyrGeodata, "onLoad", buildLayerList);
		dojo.connect(lyrGeodata, "onLoad", updateActiveLayersList);
	}

	drawToolbar = new esri.toolbars.Draw(myMap)
	drawToolbar.setFillSymbol(symAoiHighlight);
	dojo.connect(drawToolbar, "onDrawEnd", drawEndSelector);
	navToolbar = new esri.toolbars.Navigation(myMap);
	dojo.connect(navToolbar, "onExtentHistoryChange", extentHistoryChangeHandler);
	dojo.connect(myMap, "onLoad", showLoading);
	dojo.connect(myMap, "onZoomStart", showLoading);
	dojo.connect(myMap, "onPanStart", showLoading);
	dojo.connect(lyrGeodata, "onUpdateEnd", function(err) {hideLoading(); if(err === undefined) {esri.hide(dojo.byId('mapError')); firstErr = 0;}});
	dojo.connect(lyrBasemap, "onUpdateEnd", storeCoords);
	dojo.connect(myMap,'onMouseMove', showCoordinates);
	dojo.connect(myMap,'onMouseDrag', showCoordinates);
	dojo.connect(myMap, "onLoad", initIdentify);
	dojo.connect(lyrGeodata, "onError", lyrGeodataErr);
	dojo.connect(myMap, "onLoad", function () {
		overviewMapDijit = new esri.dijit.OverviewMap({
			maximizeButton: false,
			baseLayer: lyrOv,
			map:myMap,
			id:'ovMap',
			color: '#FF2A55',
			width: 200,
			height: 100,
			attachTo: 'bottom-right',
			visible: true
		});
		overviewMapDijit.startup();
		var legendLayer = [];
		legendLayer.push({layer:lyrGeodata, title: 'Datasets'});
		geoLegend = new esri.dijit.Legend({
			map:myMap,
			layerInfos: [{layer:lyrGeodata, title: 'Datasets'}]
		},"legendDiv");
		geoLegend.startup();
		navToolbar.activate(esri.toolbars.Navigation.ZOOM_IN);
	});
	dojo.connect(dijit.byId("mapDiv"), 'resize', resizeMap);
	// dojo.connect(myMap,"onPanEnd", function() {128zt}); - removed this, is it really needed? When active, the panning didn't work as it should...
	dojo.connect(dijit.byId("paneLegend"),"onShow", function() {geoLegend.refresh();storeCoords();});
	dojo.connect(dijit.byId("paneToc"),"onShow", function() {refreshTree();storeCoords();});
	dojo.connect(dijit.byId("paneAoi"),"onShow", function() {storeCoords();});
	dojo.connect(dijit.byId("paneActive"),"onShow", function() {refreshTree();updateActiveLayersList();storeCoords();});
	dojo.connect(dijit.byId("paneSource"),"onShow", function() {storeCoords();});
	dojo.connect(dijit.byId("paneContact"),"onShow", function() {storeCoords();});
	dojo.connect(dijit.byId("paneAbout"),"onShow", function() {storeCoords();});
	myMap.addLayer(searchGfxLayer);
	myMap.addLayer(aoiGfxLayer);
	if (document.cookie.replace(new RegExp('.*aoi' + thisView + '.*'),'yes') == 'yes') {
		dojo.connect(myMap, "onLoad", displayAoiBox);
	}
	if (thisTool != undefined) dojo.connect(myMap, 'onLoad', function(){toggleButtonIcon(dijit.byId(thisTool)); dijit.byId(thisTool).onClick();});
	dojo.connect(lyrGeodata,'onLoad', refreshQueryField);
	dojo.connect(dijit.byId("zoomin"),"onClick", function() {curTool = 'zoomin';});
	dojo.connect(dijit.byId("pan"),"onClick", function() {curTool = 'pan';});
	dojo.connect(dijit.byId("identify"),"onClick", function() {curTool = 'identify';});
	dojo.connect(dijit.byId("selectarea"),"onClick", function() {curTool = 'selectarea';});
}
var firstErr = 0;
function lyrGeodataErr(Err) {
	firstErr++;
	if (firstErr == 1) {
		lyrGeodata.refresh();
	} else {
		if (firstErr == 2) {
			alert ('The datasets layer is not loading due to server or communications issues. Please try to reload the map, try the "reset map" button to the lower left, or check again in a short while. Thank you for your patience!');
			esri.show(dojo.byId('mapError'));
		}
	}
}
function storeCoords() {
	// Stores settings in the cookie for permanence
	document.cookie = 'ext' + thisView + '=' + myMap.extent.xmax + ',' + myMap.extent.ymax + ',' + myMap.extent.xmin + ',' + myMap.extent.ymin +'; expires=Fri, 3 Aug 2051 20:47:11 UTC; path=' + document.location.href.replace(/http:..[a-z.]+/,'');
	document.cookie = 'aoi' + thisView + '=' + document.getElementById('aoiNorth').value + ',' + document.getElementById('aoiEast').value + ',' + document.getElementById('aoiSouth').value + ',' + document.getElementById('aoiWest').value +'; expires=Fri, 3 Aug 2051 20:47:11 UTC; path=' + document.location.href.replace(/http:..[a-z.]+/,'');
	document.cookie = 'cView=' + thisView +'; expires=Fri, 3 Aug 2051 20:47:11 UTC; path=' + document.location.href.replace(/http:..[a-z.]+/,'');
	var thisPane = dijit.byId('leftAccordion').selectedChildWidget.id;
	thisPane = (thisPane == 'paneQuery' ? 'paneToc' : thisPane);
	document.cookie = 'pane' + thisView + '=' + thisPane +'; expires=Fri, 3 Aug 2051 20:47:11 UTC; path=' + document.location.href.replace(/http:..[a-z.]+/,'');
	document.cookie = 'tool' + thisView + '=' + curTool +'; expires=Fri, 3 Aug 2051 20:47:11 UTC; path=' + document.location.href.replace(/http:..[a-z.]+/,'');
}
function resizeMap() {
	//resize the map when the browser resizes - view the 'Resizing and repositioning the map' section in
	//the following help topic for more details http://help.esri.com/EN/webapi/javascript/arcgis/help/jshelp_start.htm#jshelp/inside_faq.htm
	var resizeTimer;
	clearTimeout(resizeTimer);
	resizeTimer = setTimeout(function() {
		myMap.resize();
		myMap.reposition();
	}, 500);
	if (navigator.userAgent.match(/MSIE 9/)) document.location.reload();
}
function extentHistoryChangeHandler() {
	dijit.byId("zoomprev").disabled = navToolbar.isFirstExtent();
	dijit.byId("zoomnext").disabled = navToolbar.isLastExtent();
}
function showLoading() {
	esri.show(loading);
	lyrGeodata.hide();
	myMap.hideZoomSlider();
}
function hideLoading(error) {
	if (!lyrGeodata.updating) {
		esri.hide(loading);
		myMap.showZoomSlider();
		if ((myMap.extent.getWidth() / lyrBasemap.fullExtent.getWidth()) > ovCutoff) {
			if (overviewMapDijit.expandFactor != 1.2) {
				overviewMapDijit.expandFactor = 1.2;
				myMap.resize();
			}
		} else {
			if (overviewMapDijit.expandFactor != 3) {
				overviewMapDijit.expandFactor = 3;
				myMap.resize();
			}
		}
		lyrGeodata.show();
	}
}
function hideLoadingForce() {
	esri.hide(loading);
	myMap.showZoomSlider();
	lyrGeodata.show();
}
function buildLayerList(layer) {
	var infos = layer.layerInfos, info;
	var items = [];
	var visible = [-1];
	lyrGeodataLyr = [];
	for (var i=0, il=infos.length; i<il; i++) {
		info = infos[i];
		if (info.defaultVisibility) {
			visible.push(info.id);
		}
		lyrGeodataLyr[info.name] = [];
		lyrGeodataLyr[info.name]['id'] = info.id;
		lyrGeodataLyr[info.name]['vis'] = info.defaultVisibility;
	}
	// Get visibility from cookie
	if (document.cookie.replace(new RegExp('.*lyr' + thisView + '.*'),'yes') == 'yes') {
		var lyrCookie = document.cookie.replace(new RegExp('.*lyr' + thisView + '=(.*)'),'$1').split(',');
		var j = 0;
		for (var i in lyrGeodataLyr) {
			if (lyrCookie[j]==1) {
				lyrGeodataLyr[i].vis = true;
				visible.push(lyrGeodataLyr[i].id);
			}
			j++;
		}
	}
	if (document.cookie.replace(new RegExp('.*act' + thisView + '.*'),'yes') == 'yes') {
		var cookieActive = document.cookie.replace(new RegExp('.*act' + thisView + '=([0-9]+)($|;.*)'),'$1');
		if (typeof(parseInt(cookieActive)) == 'number') activeCurr = parseInt(cookieActive);
	}
	layer.setVisibleLayers(visible);
	myMap.addLayer(layer);
	refreshTree();
}
function updateActiveLayersList() {
	// Update active layers list
	var items = []
	var countItems = 0
	for (var i in lyrGeodataLyr) {
		if (lyrGeodataLyr[i].vis) {
			countItems++;
			if (activeCurr == -1) {activeCurr = lyrGeodataLyr[i].id;}
		} else {
			if(lyrGeodataLyr[i].id == activeCurr) {activeCurr = -1;}
		}
	}
	for (var i in lyrGeodataLyr) {
		j = lyrGeodataLyr[i];
		if (j.vis) {
			var isChecked = '';
			if (countItems == 1 || activeCurr == j.id) {
				isChecked = 'checked = "checked"';
				activeCurr = j.id;
			}
			items.push("<li><input name='active' type='radio' " + isChecked + " class='list_item' id='al" + j.id + "' value='true' onclick='activeCurr = " + j.id + "; updateLayerVisibility(); myMap.infoWindow.hide();' /><label for='al" + j.id + "'>" + i + "</label></li>");
		}
	}
	dojo.byId("activeList").innerHTML = items.join('');
}
function updateLayerVisibility(doRedraw) {
	esri.show(loading);
	clearSearch();
	layersLoaded = myMap.layerIds.length-1;
	visible = [-1];
	/*
	var inputs = dojo.query(".list_item"), input;
	for (var i=0, il=inputs.length; i<il; i++) {
	  if (inputs[i].checked) {
		visible.push(inputs[i].id);
	  }
	}
	*/
	var lyrCookieString = '';
	for (var i in lyrGeodataLyr) {
		if (lyrGeodataLyr[i].vis) visible.push(lyrGeodataLyr[i].id);
		lyrCookieString = lyrCookieString + (lyrGeodataLyr[i].vis ? 1 : 0) + ',';
	}
	lyrGeodata.setVisibleLayers(visible);
	geoLegend.refresh();
	updateActiveLayersList();
	document.cookie = 'lyr' + thisView + '=' + lyrCookieString + '; expires=Fri, 3 Aug 2051 20:47:11 UTC; path=' + document.location.href.replace(/http:..[a-z.]+/,'');
	document.cookie = 'act' + thisView + '=' + activeCurr + '; expires=Fri, 3 Aug 2051 20:47:11 UTC; path=' + document.location.href.replace(/http:..[a-z.]+/,'');
	refreshQueryField();
}
// {{{ IDENTIFY STUFF
	function activeLayersArray() {
		var outArray = [];
		outArray.push(activeCurr);
		return outArray;
	}
	function initIdentify(map) {
		dojo.connect(map, "onClick", doIdentify);
		identifyTask = new esri.tasks.IdentifyTask("http://maps.continentalshelf.org/ArcGIS/rest/services/shelfdatashop_geodata_wgs84/MapServer");
		identifyParams = new esri.tasks.IdentifyParameters();
		identifyParams.tolerance = 3;
		identifyParams.returnGeometry = true;
		identifyParams.layerIds = activeLayersArray();
		identifyParams.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_ALL;
		identifyParams.width  = map.width;
		identifyParams.height = map.height;
		map.infoWindow.resize(300, 200);
		map.infoWindow.setTitle("Identify Results");
	}
	function doIdentify(evt) {
		clearSearch();
		updateActiveLayersList();
		myMap.infoWindow.hide();
		showLoading();
		identifyParams.geometry = evt.mapPoint;
		identifyParams.mapExtent = myMap.extent;
		identifyParams.layerIds = activeLayersArray();
		identifyTask.execute(identifyParams, function(idResults) { addToMap(idResults, evt); });
	}
	function infoPoint (results,i) {
		var dispPoint;
		var isValid = false;
		try {
			if (i < results.length) isValid = true;
			if (results[i].feature != undefined) isValid = true;
			if (results[i].feature != undefined && results[i].feature.geometry._extent != undefined) isValid = true;
			if (results[i].geometry != undefined) isValid = true;
			if (results[i].geometry != undefined && results[i].geometry._extent != undefined) isValid = true;
		}
		catch(err) {
			isValid = false;
		}
		if (isValid) {
			if (results[i].feature != undefined) {
				if (results[i].feature._extent != undefined) {
					var thisExtent = results[i].feature._extent;
				} else {
					var thisExtent = results[i].feature.geometry._extent;
				}
			} else {
				if (results[i]._extent != undefined) {
					var thisExtent = results[i]._extent;
				} else {
					var thisExtent = results[i].geometry._extent;
				}
			}
			var pointX = (thisExtent.xmax + thisExtent.xmin) / 2
			var pointY = (thisExtent.ymax + thisExtent.ymin) / 2
			dispPoint = new esri.geometry.Point([pointX,pointY],new esri.SpatialReference({ wkid:4326 }));
		} else {
			dispPoint = new esri.geometry.Point([myMap.extent.xmin,myMap.extent.ymin],new esri.SpatialReference({ wkid:4326 }));
		}
		return dispPoint;
	}
	function featureExtent (results,i) {
		// Gets a new extent from the feature passed in, and gets the extent for the map to zoom to and returns it
		var isValid = false;
		try {
			if (i < results.length) isValid = true;
			if (results[i].feature != undefined) isValid = true;
			if (results[i].feature != undefined && results[i].feature.geometry._extent != undefined) isValid = true;
			if (results[i].geometry != undefined) isValid = true;
			if (results[i].geometry != undefined && results[i].geometry._extent != undefined) isValid = true;
		}
		catch(err) {
			isValid = false;
		}
		if (isValid) {
			if (results[i].feature != undefined) {
				if (results[i].feature._extent != undefined) {
					var thisExtent = results[i].feature._extent;
				} else {
					var thisExtent = results[i].feature.geometry._extent;
				}
			} else {
				if (results[i]._extent != undefined) {
					var thisExtent = results[i]._extent;
				} else {
					var thisExtent = results[i].geometry._extent;
				}
			}
			for (var j=0;j<4;j++) {
				var thisWidth = thisExtent.xmax - thisExtent.xmin;
				var thisHeight = thisExtent.ymax - thisExtent.ymin;
				var factor = 0.2;
				thisExtent.xmin = thisExtent.xmin - thisWidth * factor;
				thisExtent.xmax = thisExtent.xmax + thisWidth * factor;
				thisExtent.ymin = thisExtent.ymin - thisHeight * factor;
				thisExtent.ymax = thisExtent.ymax + thisHeight * factor;
			}
		} else {
			thisExtent = myMap.extent;
		}
		return thisExtent;
	}
	function addToMap(idResults, evt, iDx) {
		hideLoadingForce();
		var infoContent = '';
		currIdResults = idResults;
		if (activeCurr == -1) {
			// if there are no active layers toggled...
			myMap.infoWindow.setContent('<h5>Active layers</h5><p>There are currently no data layers visible</p>');
			if (evt != null) {
				myMap.infoWindow.setTitle('Results');
				myMap.infoWindow.show(evt.screenPoint, myMap.getInfoWindowAnchor(evt.screenPoint));
			}
			return;
		}
		var hypField = 'OBJECTID', hypPre, hypSuff, isHyperLink;
		var hypField2 = '', hypPre2, hypSuff2;
		if (idResults.length > 0) {
			var isHyperLink = !(hyperLayers[idResults[0].layerName].hyperfield === undefined);
			if (isHyperLink) {
				hypField = hyperLayers[idResults[0].layerName].hyperfield;
				hypPre = hyperLayers[idResults[0].layerName].hyperprefix;
				hypSuff = hyperLayers[idResults[0].layerName].hypersuffix;
				if (!(hyperLayers[idResults[0].layerName].hyperfield2 === undefined)) {
					hypField2 = hyperLayers[idResults[0].layerName].hyperfield2;
					hypPre2 = hyperLayers[idResults[0].layerName].hyperprefix2;
					hypSuff2 = hyperLayers[idResults[0].layerName].hypersuffix2;
				}
			}
		}
		if (idResults.length == 1 || iDx != null) {
			if (iDx != null) {
				i = iDx;
				infoContent = '<div style="FLOAT: Right;"><a href="#" onclick="dispFeature(null); return false;">Return to list</a></div>';
			} else {
				i = 0;
			}
			infoContent = infoContent + '<table class="att">';
			var attr = idResults[i].feature.attributes;
			for (var attField in attr) {
				if (attField in {'OBJECTID':'', 'Shape':'','Shape.area':'','Shape.len':''} == false && (hyperLayers[idResults[i].layerName].hide != undefined && !(attField in oc(hyperLayers[idResults[i].layerName].hide)))) {
				// if (attField in {'OBJECTID':'', 'Shape':'','Shape.area':'','Shape.len':''} == false) {
					if (attField in oc(hypField) && attr[attField].length > 0) {
						infoContent = infoContent + '<tr><td class="attName">' + attField + '</td><td><a href="' + hypPre + attr[attField] + hypSuff + '" target="_blank">' + beautLink(hypPre + attr[attField] + hypSuff, attr[attField]) + '<img src="new_window_icon.png" width="9" height="9" alt="Open in new window/tab" /></a>&nbsp;</td></tr>';
					} else {
						if (attField in oc(hypField2) && attr[attField].length > 0) {
							infoContent = infoContent + '<tr><td class="attName">' + attField + '</td><td><a href="' + hypPre2 + attr[attField] + hypSuff2 + '" target="_blank">' + beautLink(hypPre2 + attr[attField] + hypSuff2, attr[attField]) + '<img src="new_window_icon.png" width="9" height="9" alt="Open in new window/tab" /></a>&nbsp;</td></tr>';

						} else {
							infoContent = infoContent + '<tr><td class="attName">' + attField + '</td><td>' + attr[attField] + '&nbsp;</td></tr>';
						}
					}
				}
			}
			infoContent = infoContent + '</table>';
			showFeature(idResults[i].feature);
		} else {
			if (idResults.length == 0) {
				infoContent = '<h5>No features found</h5>';
			} else {
				infoContent = '';
				infoContent = infoContent + '<ul>';
				for (var i=0, il=idResults.length; i<il; i++) {
					infoContent = infoContent + '<li><a href="#" onclick="dispFeature(' + i + '); return false;">' + idResults[i].feature.attributes[hyperLayers[idResults[0].layerName].refid] + '</a></li>';
				}
				infoContent = infoContent + '</ul>';
			}
		}
		myMap.infoWindow.setContent(infoContent);
		myMap.infoWindow.setTitle((idResults != 0 ? idResults[0].layerName : 'Identify'));
		if (evt != null) {
			myMap.infoWindow.show(evt.screenPoint, myMap.getInfoWindowAnchor(evt.screenPoint));
		} else {
			myMap.infoWindow.show(infoPoint(idResults,i));
		}
	}
	function dispFeature(i) {
		clearSearch();
		addToMap(currIdResults, null, i);
	}
	function highlightFeatureSymbol(feature){
		switch (feature.geometry['type']) {
			case "point":
				return symSearchPoint ;
			break;
			case "polygon":
				return symSearchPoly;
			break;
			case "polyline":
				return symSearchPolyLine;
			break;
		}
	}
	function showFeature(feature) {
		clearSearch();
		feature.setSymbol(highlightFeatureSymbol(feature));
		searchGfxLayer.add(feature);
	}
// }}}
dojo.addOnLoad(init);

// {{{ TREE FOR BOXES
	var treeStore, treeModel, tree, expandedNodes = new Array();
	dojo.addOnLoad(function() {
		treeStore = new dojo.data.ItemFileWriteStore( {
			url: "geodata.json"
		});
		treeModel = new tmpdir.CheckBoxStoreModel( {
			store: treeStore,
			query: {type: 'group'},
			checkboxAll:  false,
			checkboxRoot: false,
			checkboxState: true,
			checkboxStrict: true
		}); 
		tree = new tmpdir.CheckBoxTree( {
			nodeIcons: false,
			model: treeModel,
			showRoot: false,
			id: "MenuTree",
			persist: false,
			autoExpand: false,
			allowMultiState: false,
			checkboxStyle: 'html',
			onClick: treeOnClick,
			branchIcons: true
		});
		function treeOnClick(item,node,event) {
			if (item.checkbox != undefined) {
				if (event.target.className != 'tmpdirHTMLCheckBox') {
					item.checkbox[0] = !item.checkbox[0];
					node._checkbox.checked = item.checkbox[0];
				}
				lyrGeodataLyr[item.name[0]].vis = item.checkbox[0];
				if (item.checkbox[0]) activeCurr = lyrGeodataLyr[item.name[0]].id;
				updateLayerVisibility();
			}
			if (node.isExpandable) {
				if (node.isExpanded) {
					tree._collapseNode(node);
				} else {
					tree._expandNode(node);
				}
			}
		}
		tree.placeAt('treeDiv');

		// {{{ HYPERLINK ARRAY + REFID ARRAY
			treeStore.fetch({query: "", onComplete: function(items,request) {
				for (var i=0; i<items.length; i++) {
					hyperLayers[items[i].name] = items[i];
					if(items[i].hide === undefined) hyperLayers[items[i].name].hide = [];
				}
			}});
		// }}}
	});
	function refreshTree() {
		var allItems = treeStore._arrayOfAllItems;
		for (var i=0; i<allItems.length; i++) {
			if (lyrGeodataLyr[allItems[i].name[0]] != undefined) {
				allItems[i].checkbox[0] = lyrGeodataLyr[allItems[i].name[0]].vis;
				if (lyrGeodataLyr[allItems[i].name[0]].vis) {
					for(var j in allItems[i]._RRM) {
						if (j != undefined) expandedNodes.push([j,allItems[i].name[0]]);
					}
				}
			}
		}
		// Completely delete every node from the dijit.Tree     
		tree._itemNodesMap = {};
		tree.rootNode.state = "UNCHECKED";
		tree.model.root.children = null;

		// Destroy the widget
		tree.rootNode.destroyRecursive();

		// Recreate the model, (with the model again)
		tree.model.constructor(treeModel);

		// Rebuild the tree
		tree.postMixInProperties();
		tree._load();
		
		// Expand nodes that with visible items
		dojo.connect(tree, 'onLoad', function() {
			for(var i=0; i<expandedNodes.length; i++) {
				tree.attr('path',['$root$',expandedNodes[i][0],expandedNodes[i][1]]);
			}
		})
	}
// }}}

// {{{ AOI STUFF
	function calcNumber(inNumber) {
		inNumber = Number(inNumber);
		if (!isNaN(inNumber)) {
			inNumber = Math.round(inNumber*100)/100;
			inNumber = Math.round(inNumber*20)/20;
			return inNumber;
		} else {
			return 0;
		}
	}
	function displayAoiBox() {
		aoiGfxLayer.clear();
		var aoiN = Number(document.getElementById('aoiNorth').value);
		var aoiS = Number(document.getElementById('aoiSouth').value);
		var aoiE = Number(document.getElementById('aoiEast').value);
		var aoiW = Number(document.getElementById('aoiWest').value);
		var aoiBox = new esri.geometry.Polyline({
			"paths":[[
				[aoiW,aoiN], [aoiE,aoiN], [aoiE,aoiS], [aoiW,aoiS], [aoiW,aoiN]
			]],
			"spatialReference":{wkid:4326}
		});
		var gAoi = new esri.Graphic(aoiBox, symAoiHighlight);
		aoiGfxLayer.add(gAoi);
		if (thisView == 'arctic_laea'){
			var fe = new esri.geometry.Extent(-9000000,-9000000,9000000,9000000, thisProj);
		} else {
			var fe = maxExtent;
		}
		aoiGfxLayer.add(new esri.Graphic(
			new esri.geometry.Rect(fe.xmin,fe.ymax,fe.getWidth(),fe.ymax - aoiN),
			symAoiGrayBox
		));
		aoiGfxLayer.add(new esri.Graphic(
			new esri.geometry.Rect(fe.xmin,aoiN,aoiW - fe.xmin, aoiN - fe.ymin),
			symAoiGrayBox
		));
		aoiGfxLayer.add(new esri.Graphic(
			new esri.geometry.Rect(aoiE,aoiN,fe.xmax - aoiE, aoiN - fe.ymin),
			symAoiGrayBox
		));
		aoiGfxLayer.add(new esri.Graphic(
			new esri.geometry.Rect(aoiW,aoiS,aoiE-aoiW, aoiS - fe.ymin),
			symAoiGrayBox
		));
		storeCoords();
	}
	function zoomToAOI() {
		var aoiN = Number(document.getElementById('aoiNorth').value);
		var aoiS = Number(document.getElementById('aoiSouth').value);
		var aoiE = Number(document.getElementById('aoiEast').value);
		var aoiW = Number(document.getElementById('aoiWest').value);
		aoiExtent = new esri.geometry.Extent(aoiW,aoiS,aoiE,aoiN, thisProj);
		myMap.setExtent(aoiExtent, true);
	}
	// {{{ DRAWING BOX RELATED...
		function drawEndSelector(geometry) {
			if (dijit.byId('selectarea').get('checked')) {
				updateActiveLayersList();
				clearSearch();
				myMap.infoWindow.hide();
				showLoading();
				selectAreafromDraw(geometry);
			} else {
				updateAOIfromDraw(geometry);
			}
		}
		function updateAOIfromDraw(geometry) {
			document.getElementById('aoiNorth').value = Math.round(geometry.ymax*100)/100
			document.getElementById('aoiSouth').value = Math.round(geometry.ymin*100)/100
			document.getElementById('aoiEast').value = Math.round(geometry.xmax*100)/100
			document.getElementById('aoiWest').value = Math.round(geometry.xmin*100)/100
			displayAoiBox();
			drawToolbar.deactivate();
			myMap.showZoomSlider();
			navToolbar.activate(esri.toolbars.Navigation.ZOOM_IN);
			dijit.byId('zoomin').set("checked",true);
			hideLoadingForce();
		}
		function selectAreafromDraw(geometry) {
			// drawToolbar.deactivate();
			// myMap.showZoomSlider();
			// navToolbar.activate(esri.toolbars.Navigation.ZOOM_IN);
			// dijit.byId('zoomin').set("checked",true);
			// dijit.byId('selectarea').set("checked",true);
			clearSearch();
			if (activeCurr == -1) {
				myMap.infoWindow.setContent('<h5>Active layers</h5><p>There are currently no data layers visible</p>');
				myMap.infoWindow.setTitle('Error');
				myMap.infoWindow.show(new esri.geometry.Point([myMap.extent.xmin,myMap.extent.ymin],new esri.SpatialReference({ wkid:4326 })),esri.dijit.InfoWindow.ANCHOR_UPPERRIGHT);
				return;
			}
			var queryTask = new esri.tasks.QueryTask("http://maps.continentalshelf.org/ArcGIS/rest/services/shelfdatashop_geodata_wgs84/MapServer/" + activeCurr);
			for (var i in qFields) {
				if (!(qFields[i].name in {"Shape":"", "Shape.area":"", "Shape.len":"", "OBJECTID":""})) {
					layFields.push(qFields[i].alias);
				}
			};
			var query = new esri.tasks.Query();
			query.geometry = geometry;
			query.outFields = layFields;
			query.returnGeometry = true;
			queryTask.execute(query,showResults,errBack);
		}
	// }}}

// }}}

// {{{ QUERY RELATED
var qFields;
function refreshQueryField() {
	dojo.xhrGet({
		url:"http://maps.continentalshelf.org/ArcGIS/rest/services/shelfdatashop_geodata_wgs84/MapServer/" + activeCurr + "?f=pjson",
		handleAs:"json",
		headers: {"X-Requested-With": ""},
		load: function(data){
			for(var i in data){
				if (i == 'fields') {qFields = data[i];}
			}
			var outForm = '<select id="qfField">';
			for (var i in qFields) {
				if (!(qFields[i].name in {"Shape":"", "Shape.area":"", "Shape.len":"", "OBJECTID":""})) {
					outForm = outForm + '<option name="' + qFields[i].name + '" value"' + qFields[i].name + '">' + qFields[i].name +'</option>';
				}
			};
			outForm = outForm + '</select>';
			if(dojo.byId('qfField')) {
				dojo.byId('qfField').innerHTML = outForm;
			}
		}
	});
}
function refreshSampleValues() {
	var outForm;
	if (dojo.byId('qfValueSelect')) {
		outForm = '<label for="qfValue">Value:</label><br />';
		outForm = outForm + '<input width="15" id="qfValue" /><br />';
		outForm = outForm + '<button name="Get sample values" onclick="querySampleValues(); return false;">Get sample values</button>';
		dojo.byId('qfValueBlock').innerHTML = outForm;
	}
}
function prepareQueryForm() {
	var outForm;
	updateActiveLayersList();
	if (thisView == 'arctic_laea'){
		dojo.byId('paneQuery').innerHTML = '<em>This functionality is not available in this view. Try switching to <a href="javascript:updateView(\'world\');">the world view</a> to enable the query form.</em>';
		return
	}
	dojo.xhrGet({
		url:"http://maps.continentalshelf.org/ArcGIS/rest/services/shelfdatashop_geodata_wgs84/MapServer/" + activeCurr + "?f=pjson",
		handleAs:"json",
		headers: {"X-Requested-With": ""},
		load: function(data){
			for(var i in data){
				if (i == 'fields') {qFields = data[i];}
			}
			// Build form
			outForm = "<form>";
			outForm = outForm + '<label for="qfField">Field:</label><br />';
			outForm = outForm + '<select id="qfField" onchange="refreshSampleValues();">';
			for (var i in qFields) {
				if (!(qFields[i].name in {"Shape":"", "Shape.area":"", "Shape.len":"", "OBJECTID":""})) {
					outForm = outForm + '<option name="' + qFields[i].name + '" value"' + qFields[i].name + '">' + qFields[i].name +'</option>';
				}
			};
			outForm = outForm + '</select><br />';
			outForm = outForm + '<label for="qfOperator">Operator:</label><br />';
			outForm = outForm + '<select name="qfOperator" id="qfOperator">';
			outForm = outForm + '<option name="=" value="=">=</option>';
			outForm = outForm + '<option name="<" value="<"><</option>';
			outForm = outForm + '<option name=">" value=">">></option>';
			outForm = outForm + '<option name="<=" value="<="><=</option>';
			outForm = outForm + '<option name=">=" value=">=">>=</option>';
			outForm = outForm + '<option name="LIKE" value="LIKE">LIKE</option>';
			outForm = outForm + '</select><br />';
			outForm = outForm + '<span id="qfValueBlock"><label for="qfValue">Value:</label><br />';
			outForm = outForm + '<input width="15" id="qfValue" /><br />';
			outForm = outForm + '<button name="Get sample values" onclick="querySampleValues(); return false;">Get sample values</button></span><br />';
			outForm = outForm + '<button name="Add to query string" onclick="updateQueryString(); return false;">Add to query string</button><br /><br />';
			outForm = outForm + '<input width="15" name="qfQueryString" id="qfQueryString"/><br />';
			outForm = outForm + '<button name="Execute" onclick="startQuery(); return false;">Execute</button>&nbsp';
			outForm = outForm + '<button name="Clear" onClick="prepareQueryForm(); return false;">Clear</button><br />';
			outForm = outForm + '</form>';
			dojo.byId('paneQuery').innerHTML = outForm;
		}
	});
}
var queryTask, query, errBack, layFields = [];
function updateQueryString() {
	// After pressing a button in the query form, this copies values into the querystring...
	var thisValue = '';
	var thisField = dojo.byId('qfField').options[dojo.byId('qfField').selectedIndex].text;
	var newQstring = dojo.byId('qfField').options[dojo.byId('qfField').selectedIndex].text  + ' ' + dojo.byId('qfOperator').options[dojo.byId('qfOperator').selectedIndex].text + ' ';
	var prevQString = dojo.byId('qfQueryString').value;
	if (dojo.byId('qfValue')) {
		thisValue = dojo.byId('qfValue').value;
		for (var i=0;i<qFields.length;i++) {
			// This little loop checks if we need to quote the value
			if (qFields[i].name == thisField) {
				if (qFields[i].type = 'esriFieldTypeString') {
					if (thisValue.substr(0,1) != "'") {
						thisValue = "'" + thisValue + "'"
					}
				}
			}
		}
	} else {
		thisValue = dojo.byId('qfValueSelect').options[dojo.byId('qfValueSelect').selectedIndex].text;
	}
	newQstring = newQstring + thisValue;
	if (prevQString.length > 0) {prevQString = prevQString + ' OR ';}
	dojo.byId('qfQueryString').value = prevQString + newQstring;
}
function querySampleValues() {
	dojo.byId('qfValueBlock').innerHTML = '<em>Loading first 500 values</em>';
	queryTask = new esri.tasks.QueryTask("http://maps.continentalshelf.org/ArcGIS/rest/services/shelfdatashop_geodata_wgs84/MapServer/" + activeCurr);
	query = new esri.tasks.Query();
	var isString = false;
	var thisField = dojo.byId('qfField').options[dojo.byId('qfField').selectedIndex].text;
	for (var i=0;i<qFields.length;i++) {
		// This little loop checks if it is a string
		if (qFields[i].name == thisField) {
			isString = (qFields[i].type == 'esriFieldTypeString');
		}
	}
	if (isString) {
		query.where = "OBJECTID > 0 AND " + dojo.byId('qfField').options[dojo.byId('qfField').selectedIndex].text + " <> '' AND NOT " + dojo.byId('qfField').options[dojo.byId('qfField').selectedIndex].text + " IS NULL";
	} else {
		query.where = "OBJECTID > 0 AND NOT " + dojo.byId('qfField').options[dojo.byId('qfField').selectedIndex].text + " IS NULL";
	}
	console.log(query.where);
	query.outFields = [dojo.byId('qfField').options[dojo.byId('qfField').selectedIndex].text];
	query.returnGeometry = false;
	queryTask.execute(query,queryShowSampleValues,errBack);
}
var featResult;
function queryShowSampleValues(results) {
	var sampleSelect = '<label for="qfValueSelect">Value:</label><br /><select id="qfValueSelect">';
	featResult = results.features;
	var queryField = dojo.byId('qfField').options[dojo.byId('qfField').selectedIndex].text;
	var prevItem = '';
	var thisItem = '';
	var allItems = [];
	featResult.sort();
	for (var i=0; i<featResult.length; i++) {
		allItems.push(featResult[i].attributes[queryField]);
	}
	allItems.sort();
	for (var i=0; i<allItems.length; i++) {
		thisItem = allItems[i];
		if (thisItem != prevItem) {
			prevItem = thisItem;
			if (typeof(thisItem) == 'string') thisItem = "'" + thisItem + "'";
			sampleSelect = sampleSelect + '<option value="' + thisItem + '">' + thisItem + '</option>';
		}
	}
	sampleSelect = sampleSelect + '</select>';
	dojo.byId('qfValueBlock').innerHTML = sampleSelect;
}
function startQuery() {
	showLoading();
	myMap.infoWindow.hide();
	queryTask = new esri.tasks.QueryTask("http://maps.continentalshelf.org/ArcGIS/rest/services/shelfdatashop_geodata_wgs84/MapServer/" + activeCurr);
	for (var i in qFields) {
		if (!(qFields[i].name in {"Shape":"", "Shape.area":"", "Shape.len":"", "OBJECTID":""})) {
			layFields.push(qFields[i].alias);
		}
	};
	query = new esri.tasks.Query();
	query.where = dojo.byId('qfQueryString').value;
	query.outFields = layFields;
	query.returnGeometry = true;
	queryTask.execute(query,showResults,errBack);
}
var qResults;
function showResults(results) {
	searchGfxLayer.clear();
	hideLoadingForce();
	qResults = results;
	var s = "";
	if (results.features.length == 0) {
		s = '<h5>No features found</h5>';
	} else {
		if (results.features.length == 1) {
			dispQFeature(0);
			return;
		} else {
			for (var j in lyrGeodataLyr) {
				if (lyrGeodataLyr[j].id == activeCurr) var thisLayerName = j;
			}
			var isHyperLink = !(hyperLayers[thisLayerName].hyperfield === undefined);
			var hypField = 'OBJECTID', hypPre, hypSuff;
			var hypField2 = '', hypPre2, hypSuff2;
			if (isHyperLink) {
				hypField = hyperLayers[thisLayerName].hyperfield;
				hypPre = hyperLayers[thisLayerName].hyperprefix;
				hypSuff = hyperLayers[thisLayerName].hypersuffix;
				if (!(hyperLayers[thisLayerName].hyperfield === undefined)) {
					hypField2 = hyperLayers[thisLayerName].hyperfield2;
					hypPre2 = hyperLayers[thisLayerName].hyperprefix2;
					hypSuff2 = hyperLayers[thisLayerName].hypersuffix2;
				}
			}
			s = '';
			s = s + '<ul>';
			for (var i=0, il=results.features.length; i<il; i++) {
				var featureAttributes = results.features[i].attributes;
				for (att in featureAttributes) {
					if (att == hyperLayers[thisLayerName].refid)
						s = s + '<li><a href="#" onclick="dispQFeature(' + i + '); return false;">' + featureAttributes[hyperLayers[thisLayerName].refid] + '</a></li>';
				}
				// Display the results in the map...
				var graphic = results.features[i];
				graphic.setSymbol(highlightFeatureSymbol(graphic));
				searchGfxLayer.add(graphic);
			}
			s = s + '</ul>';
		}
	}
	myMap.infoWindow.setContent(s);
	myMap.infoWindow.setTitle(thisLayerName);
	myMap.infoWindow.show(new esri.geometry.Point([myMap.extent.xmin,myMap.extent.ymin],new esri.SpatialReference({ wkid:4326 })),esri.dijit.InfoWindow.ANCHOR_UPPERRIGHT);
}
function dispQFeature(IDx) {
	var infoContent = '';
	for (var i in lyrGeodataLyr) {
		if (lyrGeodataLyr[i].id == activeCurr) var thisLayerName = i;
	}
	var isHyperLink = !(hyperLayers[thisLayerName].hyperfield === undefined);
	var hypField = 'OBJECTID', hypPre, hypSuff;
	var hypField2 = '', hypPre2, hypSuff2;
	if (isHyperLink) {
		hypField = hyperLayers[thisLayerName].hyperfield;
		hypPre = hyperLayers[thisLayerName].hyperprefix;
		hypSuff = hyperLayers[thisLayerName].hypersuffix;
		if (!(hyperLayers[thisLayerName].hyperfield2 === undefined)) {
			hypField2 = hyperLayers[thisLayerName].hyperfield2;
			hypPre2 = hyperLayers[thisLayerName].hyperprefix2;
			hypSuff2 = hyperLayers[thisLayerName].hypersuffix2;
		}
	}
	if (qResults.features.length > 1) {infoContent = '<div style="FLOAT: Right;"><a href="#" onclick="showResults(qResults); return false;">Return to list</a></div>';}
	infoContent = infoContent + '<table class="att">';
	var attr = qResults.features[IDx].attributes;
	if (isHyperLink) {
	}
	for (var attField in attr) {
		if (attField in {'OBJECTID':'', 'Shape':'','Shape.area':'','Shape.len':''} == false && (hyperLayers[thisLayerName].hide != undefined && !(attField in oc(hyperLayers[thisLayerName].hide)))) {
			if (isHyperLink && attField in oc(hypField) && attr[attField].length > 0) {
				infoContent = infoContent + '<tr><td class="attName">' + attField + '</td><td><a href="' + hypPre + attr[attField] + hypSuff + '" target="_blank">' + beautLink(hypPre + attr[attField] + hypSuff, attr[attField]) + '<img src="new_window_icon.png" width="9" height="9" alt="Open in new window/tab" /></a></td></tr>';
			} else {
				if (isHyperLink && attField in oc(hypField2) && attr[attField].length > 0) {
					infoContent = infoContent + '<tr><td class="attName">' + attField + '</td><td><a href="' + hypPre2 + attr[attField] + hypSuff2 + '" target="_blank">' + beautLink(hypPre2 + attr[attField] + hypSuff2, attr[attField]) + '<img src="new_window_icon.png" width="9" height="9" alt="Open in new window/tab" /></a></td></tr>';
				} else {
					infoContent = infoContent + '<tr><td class="attName">' + attField + '</td><td>' + attr[attField] + '&nbsp;</td></tr>';
				}
			}
		}
	}
	infoContent = infoContent + '</table>';
	showFeature(qResults.features[IDx]);
	myMap.infoWindow.setContent(infoContent);
	myMap.infoWindow.setTitle(thisLayerName);
	myMap.infoWindow.show(infoPoint(qResults.features,IDx));
	myMap.setExtent(featureExtent(qResults.features,IDx),true); // zooms the main map to the selected feature
}
function errBack(thisError) {
	console.log(thisError);
	myMap.infoWindow.setContent('Query failed - likely due to syntax error');
	myMap.infoWindow.setTitle("Query Results");
	myMap.infoWindow.show(new esri.geometry.Point([myMap.extent.xmin,myMap.extent.ymin],new esri.SpatialReference({ wkid:4326 })),esri.dijit.InfoWindow.ANCHOR_UPPERRIGHT);
}
// }}} 
function toggleButtonIcon(tool) {
	//only the tools in the toolbar are dijit togglebuttons so can iterate thru them
	document.cookie = 'tool' + thisView + '=' + tool.id +'; expires=Fri, 3 Aug 2051 20:47:11 UTC; path=' + document.location.href.replace(/http:..[a-z.]+/,'');
	dijit.registry.byClass("dijit.form.ToggleButton").forEach(function(togbtn) {
		togbtn.attr("checked", false);
		if (togbtn == tool) {
			togbtn.attr("checked", true);
		}
	});
}
function doZoomOut(curExtent) {
	var curWidth = curExtent.xmax - curExtent.xmin;
	var curHeight = curExtent.ymax - curExtent.ymin;
	var newxmin = (curExtent.xmin + curWidth/2) - (curWidth * 1.8)/2;
	var newxmax = newxmin + curWidth*1.8;
	var newymin = (curExtent.ymin + curHeight/2) - (curHeight*1.8)/2;
	var newymax = newymin + curHeight*1.8;
	return new esri.geometry.Extent(newxmin,newymin,newxmax,newymax, thisProj);
}
// {{{ MOUSE MOVE FUNCTIONALITY
function showCoordinates(evt) {
	if (thisView == 'arctic_laea'){
		dojo.byId("coordsDiv").innerHTML = evt.mapPoint.x.toFixed(0) + ", " + evt.mapPoint.y.toFixed(0);
	} else {
		dojo.byId("coordsDiv").innerHTML = evt.mapPoint.x.toFixed(2) + ", " + evt.mapPoint.y.toFixed(2);
	}
}
// }}}
function resetMap() {
	// Deletes all cookie information
	var views = ['geographic','arctic_laea'];
	var settings = ['ext','aoi','pane','lyr','act','tool'];
	var paths = ['/','/' + document.location.href.split('/')[3] + '/'];
	var expDate = new Date();
	expDate.setTime(expDate.getTime()-1)
	expDate = expDate.toGMTString();
	for(var i=0;i<views.length;i++) {
		for(var j=0;j<paths.length;j++) {
			for(var n=0;n<settings.length;n++) {
				document.cookie = settings[n] + views[i] + '=; expires=' + expDate + '; path=' + paths[j];
				document.cookie = 'MenuTreeSaveStateCookie=; expires=' + expDate + '; path=' + paths[j];
				document.cookie = 'cView=; expires=' + expDate + '; path=' + paths[j];
			}
		}
	}
	window.location.reload();
}
function updateView(newView) {
	// Reloads the map in the 'other' view
	var thisURL = document.location.href.replace(/#($|.*)/,'');
	document.location.href = thisURL + '?' + newView;
}

