﻿dojo.require("dijit.layout.AccordionContainer");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("esri.dijit.Legend");
dojo.require("esri.dijit.Scalebar");
dojo.require("esri.geometry");
dojo.require("esri.layers.agstiled");
dojo.require("esri.map");
dojo.require("esri.tasks.geometry");
dojo.require("esri.tasks.locator");
dojo.require("esri.tasks.query");
dojo.require("esri.toolbars.draw");
dojo.require("esri.toolbars.navigation");
/*
The identify class contains all methods necessary to handle a click on the map surface to identify a feature.
*/
cadastral.identify = {
	/*
	Handler for the click event on the map surface to identify a feature.
	*/
	identifyIt: function (evt) {
		cadastral.base.showLoading();
		// Disconnect the upMapUpdateEnd listener so that we show the loading symbol uninterrupted until the final map displays
		// We connect it again when we run the queryTask to get the parcel geometry in the setupIdentifyResults function.
		dojo.disconnect(cadastral.onMapUpdateEndConnection);
		var identifyTask = new esri.tasks.IdentifyTask(cadastral.streetUrl);
		var identifyParams = new esri.tasks.IdentifyParameters();
		identifyParams.tolerance = 3;
		identifyParams.returnGeometry = true;
		identifyParams.layerIds = [33];
		identifyParams.geometry = evt.mapPoint;
		identifyParams.mapExtent = cadastral.map.extent;
		identifyParams.height = cadastral.map.height;
		identifyParams.width = cadastral.map.width;
		identifyTask.execute(identifyParams, function (idResults) { cadastral.identify.setupIdentifyResults(idResults, evt); }, function (idResults) { cadastral.base.showError(idResults, evt); });

		// we are going to use the point clicked later to center the map
		cadastral.identify.identifyPoint = evt.mapPoint;

		// If the property record card is already visible, go ahead and center the map now, not later
		if (dojo.style("propertyCard", "visibility") == "visible") {
			cadastral.map.centerAt(evt.mapPoint);
			cadastral.identify.identifyPoint = null;
		}
	},

	identifyPoint: null,

	/*
	Handles the callback from the identifyTask. Retrieves the geocode from the result set and determines which service method to call to get data for the appropriate active property card pane.
	*/
	setupIdentifyResults: function (idResults, evt) {
		cadastral.map.graphics.clear();

		var feature = null;

		for (var i = 0; i < idResults.length; i++) {
			if (idResults[i].feature.attributes["PARCELID"] !== "") {
				feature = idResults[i].feature;
				break;
			}
		}
		cadastral.onMapUpdateEndConnection = dojo.connect(cadastral.map, "onUpdateEnd", cadastral.base.onMapUpdateEnd);
		if (feature !== null) {
			cadastral.geocode = feature.attributes["PARCELID"];

			cadastral.base.addGraphicToMap(feature.geometry);

			cadastral.base.showPropertyCard();

			switch (cadastral.activePane) {
				case "summaryPane":
					cadastral.identify.getSummaryData();
					break;
				case "ownersPane":
					cadastral.identify.getOwnerData();
					break;
				case "commercialBuildingsPane":
					cadastral.identify.getCommercialData();
					break;
				case "appraisalsPane":
					cadastral.identify.getAppraisalData();
					break;
				case "marketLandPane":
					cadastral.identify.getMarketLandData();
					break;
				case "otherBuildingsPane":
					cadastral.identify.getOtherBuildingData();
					break;
				case "dwellingPane":
					cadastral.identify.getDwellingData();
					break;
				case "agForestPane":
					cadastral.identify.getAgForestData();
					break;
				default:
					cadastral.identify.getSummaryData();
					break;
			}

		}
		else {
			if (dojo.style("propertyCard", "visibility") != "visible") {
				cadastral.base.hideLoading();
			}
			cadastral.onMapUpdateEndConnection = dojo.connect(cadastral.map, "onUpdateEnd", cadastral.base.onMapUpdateEnd);
			alert("Could not retrieve a parcel id for this location. You are probably zoomed out to far, or there is no parcel id for this parcel.");
		}
	},

	getSummaryData: function () {
		cadastral.activePane = "summaryPane";
		dojo.xhrGet({
			url: "./Summary/GetSummaryData",
			content: { geocode: cadastral.geocode, year: cadastral.taxYear },
			handleAs: "json",
			load: function (rdata) {
				cadastral.base.showData(rdata, 'summaryPane');
			}
		});
	},

	getOwnerData: function () {
		cadastral.activePane = "ownersPane";
		dojo.xhrGet({
			url: "./Owner/GetOwnerData",
			content: { geocode: cadastral.geocode, year: cadastral.taxYear },
			handleAs: "json",
			load: function (rdata) {
				cadastral.base.showData(rdata, 'ownersPane');
			}
		});
	},

	getCommercialData: function () {
		cadastral.activePane = "commercialBuildingsPane";
		dojo.xhrGet({
			url: "./Commercial/GetCommercialData",
			content: { geocode: cadastral.geocode, year: cadastral.taxYear },
			handleAs: "json",
			load: function (rdata) {
				cadastral.base.showData(rdata, 'commercialBuildingsPane');
			}
		});
	},

	getCommercialDataById: function (buildingId) {
		cadastral.activePane = "commercialBuildingsPane";
		dojo.xhrGet({
			url: "./Commercial/GetCommercialDataById",
			content: { geocode: cadastral.geocode, year: cadastral.taxYear, buildingId: buildingId },
			handleAs: "json",
			load: function (rdata) {
				cadastral.base.showData(rdata, 'commercialBuildingsPane');
			}
		});
	},

	getAppraisalData: function () {
		cadastral.activePane = "appraisalsPane";
		dojo.xhrGet({
			url: "./Appraisal/GetAppraisalData",
			content: { geocode: cadastral.geocode, year: cadastral.taxYear },
			handleAs: "json",
			load: function (rdata) {
				cadastral.base.showData(rdata, 'appraisalsPane');
			}
		});
	},

	getMarketLandData: function () {
		cadastral.activePane = "marketLandPane";
		dojo.xhrGet({
			url: "./MarketLand/GetMarketLandData",
			content: { geocode: cadastral.geocode, year: cadastral.taxYear },
			handleAs: "json",
			load: function (rdata) {
				cadastral.base.showData(rdata, 'marketLandPane');
			}
		});
	},

	getOtherBuildingData: function () {
		cadastral.activePane = "otherBuildingsPane";
		dojo.xhrGet({
			url: "./OtherBuilding/GetOtherBuildingData",
			content: { geocode: cadastral.geocode, year: cadastral.taxYear },
			handleAs: "json",
			load: function (rdata) {
				cadastral.base.showData(rdata, 'otherBuildingsPane');
			}
		});
	},

	getDwellingData: function () {
		cadastral.activePane = "dwellingPane";
		dojo.xhrGet({
			url: "./Dwelling/GetDwellingData",
			content: { geocode: cadastral.geocode, year: cadastral.taxYear },
			handleAs: "json",
			load: function (rdata) {
				cadastral.base.showData(rdata, 'dwellingPane');
			}
		});
	},

	getDwellingDataById: function (dwellingId) {
		cadastral.activePane = "dwellingPane";
		dojo.xhrGet({
			url: "./Dwelling/GetDwellingDataById",
			content: { geocode: cadastral.geocode, year: cadastral.taxYear, dwellingId: dwellingId },
			handleAs: "json",
			load: function (rdata) {
				cadastral.base.showData(rdata, 'dwellingPane');
			}
		});
	},

	getAgForestData: function () {
		cadastral.activePane = "agForestPane";
		dojo.xhrGet({
			url: "./AgForest/GetAgForestData",
			content: { geocode: cadastral.geocode, year: cadastral.taxYear },
			handleAs: "json",
			load: function (rdata) {
				cadastral.base.showData(rdata, 'agForestPane');
			}
		});
	}
};


cadastral.measure = {
	outputDistance: function (result) {
		//alert(dojo.number.format(result.lengths[0] / 1000) + " kilometers");
		dojo.byId("distance").innerHTML = dojo.number.format(result.lengths[0] / 1000 / 1.609344) + " miles";
	},

	addToMap: function (geometry) {
		var graphic = cadastral.base.addGraphicToMap(geometry);
		cadastral.measure.getDistance(graphic.geometry);
	},

	getDistance: function (geometry) {
		var lengthParams = new esri.tasks.LengthsParameters();
		lengthParams.polylines = [geometry];
		lengthParams.lengthUnit = esri.tasks.GeometryService.UNIT_METER;
		lengthParams.geodesic = true;
		cadastral.geometryService.lengths(lengthParams);
	},

	/*
	Handles click event for the maps button on the button bar. Displays the maps pane and displays all available layers.
	*/
	startup: function () {
		cadastral.base.setActiveTool("measureButton");
	}
};

cadastral.print = {
	/*
	Handles click event for the print button on the button bar. Displays the maps pane and displays all available layers.
	*/
	printTheMap: function () {
		printMap(cadastral.map);
	}
};

/*
Handles all initialization steps for the application.
*/
function init() {
	if (dojo.isIE <= 7) {
		var top = (parseInt(Math.round(dojo.style("mapDiv", "height")) / 2 - 75)) + 'px';
		var left = (parseInt(Math.round(dojo.style("mapDiv", "width")) / 2 - 100)) + 'px';
		dojo.style("ie7Div", "top", top);
		dojo.style("ie7Div", "left", left);
		dojo.style("ie7Div", "width", "400px");
		dojo.style("ie7Div", "visibility", "visible");
	} else {
		// Some events will use the proxy (drawing a buffer, measuring)
		esriConfig.defaults.io.proxyUrl = "proxy.ashx";
		esriConfig.defaults.io.alwaysUseProxy = false;

		cadastral.map = new esri.Map("mapDiv", { extent: cadastral.initialExtent, logo: false, lods: cadastral.lods });

		// Configure all the layers of the map
		cadastral.topo = cadastral.base.initDynamicLayer(cadastral.topoUrl, "topo", false, "1.0");
		cadastral.satellite = cadastral.base.initDynamicLayer(cadastral.satelliteUrl, "satellite", false, "1.0");
		cadastral.street = cadastral.base.initDynamicLayer(cadastral.streetUrl, "street", true, "1.0");
		cadastral.baseLayerArray = [cadastral.street, cadastral.satellite, cadastral.topo];

		// Set up the address locator and geometry service
		cadastral.addressLocator = new esri.tasks.Locator(cadastral.addressLocatorUrl);
		cadastral.addressLocator.outSpatialReference = cadastral.map.spatialReference;
		dojo.connect(cadastral.addressLocator, "onAddressToLocationsComplete", cadastral.search.getLocatorResults);
		dojo.connect(cadastral.addressLocator, "onError", cadastral.search.locatorError);
		cadastral.geometryService = new esri.tasks.GeometryService(cadastral.geometryServiceUrl);

		// Set the default extent
		cadastral.map.setLevel(cadastral.maxLevel);

		// Wire up some default listeners
		dojo.connect(cadastral.map, "onPanStart", cadastral.base.showLoading);
		dojo.connect(cadastral.map, "onUpdateStart", cadastral.base.showLoading);
		dojo.connect(cadastral.map, "onLoad", function () { cadastral.map.hideZoomSlider(); });
		dojo.connect(cadastral.map, "onZoomEnd", cadastral.base.onZoomEnd);
		cadastral.onMapUpdateEndConnection = dojo.connect(cadastral.map, "onUpdateEnd", cadastral.base.onMapUpdateEnd);
		dojo.connect(dijit.byId("mapDiv"), "resize", cadastral.base.resizeMap);
		// When the distance is computed, we show the distance drawn (measure tool)
		dojo.connect(cadastral.geometryService, "onLengthsComplete", cadastral.measure.outputDistance);
		// initialize drawing toolbar for measure tool
		cadastral.toolbar = new esri.toolbars.Draw(cadastral.map);
		// Set the default click event for the map
		cadastral.mapOnClickListeners.push(dojo.connect(cadastral.map, "onClick", cadastral.identify.identifyIt));

		// initialize navigation toolbar for extent history
		cadastral.tools.navToolbar = new esri.toolbars.Navigation(cadastral.map);
		dojo.connect(cadastral.tools.navToolbar, "onExtentHistoryChange", cadastral.tools.extentHistoryChangeHandler);

		//dojo.connect(cadastral.map, "onExtentChange", function () { dojo.byId("info").innerHTML = esri.geometry.getScale(cadastral.map); });

		// Set up the scale bar
		var scalebar = new esri.dijit.Scalebar({
			map: cadastral.map,
			scalebarUnit: 'english'
		});

		// This is the zoom effect when the map is zoomed in or out
		esriConfig.defaults.map.zoomDuration = 1000; // default is 250
		esriConfig.defaults.map.zoomRate = 50; // default is 25

		// Turn on the identify tool as the default
		cadastral.base.setActiveTool("identifyButton");

		// If you uncomment the section below and then zoom in on the map, it will render a legend that you can then create a legend image from
		// Create the legend for the land ownership layer
		//	var legendLayers = [];
		//	legendLayers.push({ layer: cadastral.street, title: 'Legend' });
		//	var legendDijit = new esri.dijit.Legend({
		//		map: cadastral.map
		//	}, "legendDiv");
		//	legendDijit.startup();		
	}
}

/*
Wires up the init method to page load
*/
dojo.addOnLoad(init);
