dojo.require("esri.map");
dojo.require("esri.tasks.query");
dojo.require("esri.tasks.find");
dojo.require("esri.tasks.geometry");
dojo.require("esri.tasks.identify");
dojo.require("dijit.layout.ContentPane");

var map, startExtent;
var queryTask, query;
var gsvc = null;
var pt = null;
var LatLong;

var identifyTask, identifyParams, symbol;
var s;

function init() {
    var layersLoaded = 0;  //varible to keep track of when all layers have been loaded.
    var loading = dojo.byId("mapLoadingImg");  //loading image. id

    map = new esri.Map("map", { nav: true });
    dojo.connect(map, "onLoad", showLoading);
    dojo.connect(map, "onLoad", initFunctionality);
    dojo.connect(map, "onZoomStart", showLoading);
    dojo.connect(map, "onPanStart", showLoading);
    //dojo.connect(map, "onExtentChange", showExtent);
    dojo.connect(map, "onExtentChange", setScaleBar);
    var streetMapLayer = new esri.layers.ArcGISDynamicMapServiceLayer("http://ags.wingis.org/ArcGIS/rest/services/ParcelBasic/MapServer");
    map.addLayer(streetMapLayer);
    dojo.connect(streetMapLayer, "onLoad", hideLoading);
    dojo.connect(streetMapLayer, "onUpdate", hideLoading);

    //build query
    queryTask = new esri.tasks.QueryTask("http://ags.wingis.org/ArcGIS/rest/services/ParcelBasic/MapServer/1");

    //build query filter
    query = new esri.tasks.Query();
    query.returnGeometry = true;
    query.outFields = [""];

    function showLoading() {
        esri.show(loading);
        map.disableMapNavigation();
        map.hideZoomSlider();
    }

    function hideLoading() {
        layersLoaded++;
        if (layersLoaded === map.layerIds.length) {
            esri.hide(loading);
            map.enableMapNavigation();
            map.showZoomSlider();
            layersLoaded = 0;
        }
    }

    gsvc = new esri.tasks.GeometryService("http://ags.wingis.org/arcgis/rest/services/Geometry/GeometryServer");
    dojo.connect(map, "onClick", projectToLatLong);

    dojo.connect(map.infoWindow, "onShow", function() {
    });
}
//********************************* END INIT *********************************

function setScaleBar() {
    var scale = ((map.extent.xmax - map.extent.xmin) / map.width) * 96;
    var divScaleMiles = document.getElementById("divScaleMiles");
    var miles, feet, measurment;
    measurment = scale;
    if (measurment < 1000) {
        miles = scale;
        divScaleMiles.innerHTML = miles.toFixed(2) + " feet";
    }
    else {
        miles = scale / 5280;
        divScaleMiles.innerHTML = miles.toFixed(2) + " miles";
    }
    if (measurment > 52800) {
        divScaleMiles.innerHTML = "";
    }
}
function showExtent(extent) {
    var link = "";
    var theExt = "";
    var PIN = '0000000000'
    s = "XMin: " + extent.xmin + "&nbsp;"
                + "YMin: " + extent.ymin + "&nbsp;"
                + "XMax: " + extent.xmax + "&nbsp;"
                + "YMax: " + extent.ymax;
    theExt = "?pin=" + PIN + "&xmax=" + extent.xmax + "&ymax=" + extent.ymax + "&xmin=" + extent.xmin + "&ymin=" + extent.ymin;
    link = "<a href=javascript:PrintWindow('http://ims.wingis.org/PrintPage_CurrentView.aspx" + theExt + "');>Print Current Map View</a>";
    dojo.byId("info").innerHTML = link;
}
//********************************* ZOOM FUNCTIONS *********************************

function zoomToParcelQuery(searchString) {
    query.where = "OBJECTID = '" + searchString + "'";
    queryTask.execute(query, showFindResults);
}

function zoomToPOIQuery(xPoint, yPoint) {
    var xMax = xPoint + 100;
    var yMax = yPoint + 100;
    var xMin = xPoint - 100;
    var yMin = yPoint - 100;

    var point = new esri.geometry.Point(xPoint, yPoint, map.spatialReference);
    var symbol = new esri.symbol.SimpleMarkerSymbol().setColor(new dojo.Color([0, 0, 255]));
    var graphic = new esri.Graphic(point, symbol);

    var newExtent = new esri.geometry.Extent();
    newExtent.xmin = xMin;
    newExtent.ymin = yMin;
    newExtent.xmax = xMax;
    newExtent.ymax = yMax;
    newExtent.spatialReference = new esri.SpatialReference({ wkid: 3436 });
    map.setExtent(newExtent);
    map.graphics.add(graphic)
}

function showFindResults(results) {
    map.graphics.clear();
    var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_NULL, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 3), new dojo.Color([0, 0, 0, 0]));
    for (var i = 0, il = results.features.length; i < il; i++) {
        var featureAttributes = results.features[i].attributes;
        var graphic = results.features[i];
        graphic.setSymbol(symbol);
        map.graphics.add(graphic);
        var selectedTaxLot = results.features[i].geometry.getExtent();
    }
    var taxLotExtent = selectedTaxLot;
    zoomToParcel(taxLotExtent);
}

function zoomToParcel(extent) {
	var newZoomExtent = new esri.geometry.Extent();
	newZoomExtent.spatialReference = new esri.SpatialReference({ wkid: 3436 });
	newZoomExtent.xmin = extent.xmin - 20;
	newZoomExtent.ymin = extent.ymin - 20;
	newZoomExtent.xmax = extent.xmax + 20;
	newZoomExtent.ymax = extent.ymax + 20;
	map.setExtent(newZoomExtent);
}

//********************************* START IDENTIFY FUNCTIONS *********************************

function initFunctionality(map) {
    dojo.connect(map, "onClick", doIdentify);

    identifyTask = new esri.tasks.IdentifyTask("http://ags.wingis.org/ArcGIS/rest/services/ParcelBasic/MapServer");

    identifyParams = new esri.tasks.IdentifyParameters();
    identifyParams.tolerance = 3;
    identifyParams.returnGeometry = true;
    identifyParams.layerIds = [1];
    identifyParams.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_ALL;

    map.infoWindow.resize(250, 125);
    map.infoWindow.setTitle("Identify Results");
    symbol = 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]));
}

function doIdentify(evt) {
    //map.graphics.clear();
    identifyParams.geometry = evt.mapPoint;
    identifyParams.mapExtent = map.extent;
    identifyTask.execute(identifyParams, function(idResults) { addToMap(idResults, evt); });
    map.infoWindow.show(evt.screenPoint, map.getInfoWindowAnchor(evt.screenPoint));

}

function addToMap(idResults, evt) {
    layer0results = { displayFieldName: null, features: [] };

    for (var i = 0, il = idResults.length; i < il; i++) {
        var idResult = idResults[i];
        if (idResult.layerId === 1) {
            if (!layer0results.displayFieldName) { layer0results.displayFieldName = idResult.displayFieldName };
            layer0results.features.push(idResult.feature);
        }
    }
    layerTabContent(layer0results, "layer0results");
}

function layerTabContent(layerResults, layerName) {
    var content = "";
    content += "<table cellspacing='0' cellpadding='1' width='95%'>";
    for (var i = 0, il = layerResults.features.length; i < il; i++) {
        content += "<tr><td colspan='2'>" + layerResults.features[i].attributes['LOPHouseNumber'] + " " + layerResults.features[i].attributes['LOPPrefixDirectional'] + " " + layerResults.features[i].attributes['LOPStreetName'] + " " + layerResults.features[i].attributes['LOPStreetSuffix'] + "</td></tr>";
        content += "<tr><td colspan='2'>Pin &nbsp;" + layerResults.features[i].attributes['DashPIN'] + " &nbsp; &nbsp;<font size=-2> <a href='#' onclick='showFeature(" + layerName + ".features[" + i + "]); return false;'>(highlight)</a> &nbsp; <a href='#' onclick='clearFeature(" + layerName + ".features[" + i + "]); return false;'>(clear)</a></font></td></tr>";
        content += "<tr><td colspan='2'><hr size='1' /></td></tr>";
    }
    content += "</tr></table>";
    map.infoWindow.setContent(LatLong + content);

}

function NewWindow_PD(pin) {
//  alert(pin);
    window.open('../ParcelDetails.aspx?Pin=' + pin, 'EditWindow', 'width=535, height=550, scrollbars=yes, resizable=yes');
}

function showFeature(feature) {
    map.graphics.clear();
    feature.setSymbol(symbol);
    map.graphics.add(feature);
}

function clearFeature(feature) {
    map.graphics.clear();
}

//*********************************LAT/LONG FUNCTIONS *********************************

function projectToLatLong(evt) {
//  map.graphics.clear();
    var point = evt.mapPoint;
    var symbol = new esri.symbol.SimpleMarkerSymbol().setStyle(esri.symbol.SimpleMarkerSymbol.STYLE_DIAMOND);
    var graphic = new esri.Graphic(point, symbol);
    var outSR = new esri.SpatialReference({ wkid: 4326 });
//  map.graphics.add(graphic);

    gsvc.project([graphic], outSR, function(features) {
        pt = features[0].geometry;
        var gpsdegy = parseInt(pt.y);
        var remainder = pt.y - (gpsdegy * 1.0);
        var gpsminy = remainder * 60.0;
        var gpsx = pt.x * -1;
        var gpsdegx = parseInt(gpsx);
        var remainder = gpsx - (gpsdegx * 1.0);
        var gpsminx = remainder * 60.0;
        LatLong = "<table width='95%'>"; //<tr><td>Lat = " + pt.y.toFixed(6) + "</td><td>Lon = " + pt.x.toFixed(6) + "</td></tr>";
        LatLong += "<tr><td>N " + gpsdegy + "&deg;" + gpsminy.toFixed(4) + "</td><td>W 0" + gpsdegx + "&deg;" + gpsminx.toFixed(4) + "</td></tr>";
        LatLong += "<tr><td colspan='2'><a target=new href=http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=" + pt.y.toFixed(6) + "," + pt.x.toFixed(6) + "&mrt=all&sll=" + pt.y.toFixed(6) + "," + pt.x.toFixed(6) + "&sspn=0.040887,0.084457&ie=UTF8&t=h&z=16>Driving Directions</a></td></tr>";
        LatLong += "<tr><td colspan='2'><hr size='1' /></td></tr></table>";
        //dojo.byId("latlong").innerHTML = LatLong
    });

}

dojo.addOnLoad(init);