﻿var adjoinersTask, adjoinersQuery;
var adjoinerFeature = null;
var adjoinerFeatures = null;
var adjoinerGraphics = null;
var adjoinerPointGraphics = null;
var adjoinerSymbol, adjoinerParcelSymbol;

function adjoiners_startup() {

    adjoinersTask = new esri.tasks.QueryTask(searchURL + "/" + parcels_layerID);
    adjoinersQuery = new esri.tasks.Query();
    adjoinersQuery.spatialRelationship = esri.tasks.Query.SPATIAL_REL_TOUCHES;
    adjoinersQuery.outFields = parcels_return_fields;
    adjoinersQuery.returnGeometry = true;

    adjoinerGraphics = new esri.layers.GraphicsLayer({ id: "adjoiners", displayOnPan: dojo.isIE ? false : true })
    adjoinerPointGraphics = new esri.layers.GraphicsLayer({ id: "adjoinerspoints", displayOnPan: dojo.isIE ? false : true })
    map.addLayer(adjoinerPointGraphics);
    map.addLayer(adjoinerGraphics);

    // Create symbols for result features
    adjoinerSymbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0, 255, 255]), 3);
    adjoinerParcelSymbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 2);
}

function doAdjoiners(pid) {

    showPanel("find");
    showSearchPanel("adjoiners");
    console.debug(parcelGraphics.graphics.length);
    if (parcelGraphics.graphics.length > 0) {
        dojo.style("adjoinersBackButton", { display: "block" });
    } else {
        dojo.style("adjoinersBackButton", { display: "none" });
    }

    clearCurrentTool();
    parcelGraphics.hide();
    bulletGraphics.hide();
    allSelectionGraphics.hide();
    adjoinerGraphics.clear();
    adjoinerPointGraphics.clear();
    map.infoWindow.hide();

    var queryTask = new esri.tasks.QueryTask(searchURL + "/" + parcels_layerID);
    var query = new esri.tasks.Query();
    query.where = fields.pid + " = '" + pid + "'";
    query.outFields = parcels_return_fields;
    query.returnGeometry = true;

    //Execute task and call showResults on completion
    queryTask.execute(query, function(results) {
        var graphic = results.features[0];
        adjoinerFeature = graphic;

        // first write the header for the adjoiners
        dojo.byId("adjoiners-header").innerHTML = dijits.custom.Parcels.adjoinerHeader(graphic);
        adjoinersQuery.where = fields.pid + " <> '" + pid + "'";
        adjoinersQuery.geometry = graphic.geometry;
        adjoinersTask.execute(adjoinersQuery, adjoinersCompleted, showSearchError);

    }, function(error) { console.debug(error); });
}

function adjoinersCompleted(results) {

    if (results.features.length > 0) {
        adjoinerFeatures = results.features;

        var report = dijits.custom.Parcels.processAdjoiners(results, true);
        dojo.byId("adjoiners-report").innerHTML = report;

        // add the graphics to the map...
        dojo.forEach(adjoinerFeatures, function(graphic, indx) {

            // add the point to the map;
            var fExtent = graphic.geometry.getExtent();
            var centerPt = new esri.geometry.Point;
            centerPt = fExtent.getCenter();
            var marker = "images/markers/marker" + (indx + 1) + ".png";
            var mSym = new esri.symbol.PictureMarkerSymbol(marker, 20, 34);
            var gPt = new esri.Graphic(centerPt, mSym);
            adjoinerPointGraphics.add(gPt);

            graphic.setSymbol(adjoinerSymbol);
            adjoinerGraphics.add(graphic);

        });

        adjoinerFeature.setSymbol(adjoinerParcelSymbol);
        adjoinerGraphics.add(adjoinerFeature);
        adjoinerGraphics.show();
        adjoinerPointGraphics.show();
        
        try {
            var fullExt = esri.graphicsExtent(adjoinerGraphics.graphics);
            if (fullExt != null)
                map.setExtent(fullExt.expand(1.1));
        } catch (Error) {
            console.warn("An Error occurred in the application in routine 'zoomToSelected'", Error);
        }

        adjoiners_show();

        console.debug("done");
    }

}

function adjoiners_GoBack() {

    parcelGraphics.show();
    bulletGraphics.show();
    allSelectionGraphics.show();
    adjoinerGraphics.clear();
    adjoinerPointGraphics.clear();
    adjoinerGraphics.hide();
    adjoinerPointGraphics.hide();
    showSearchPanel("results");

}

function clearAdjoiners() {
    adjoinerGraphics.clear();
    adjoinerPointGraphics.clear();
    showSearchPanel("about");
}

function showAdjoinerDetails(index) {

    // zoom to the graphic and highlight
    try {
        var detailGraphic = adjoinerGraphics.graphics[index];
        if (detailGraphic != null) {

            var parcels_content = dijits.custom.Parcels.getDetails(detailGraphic);
            infoTemplate = new esri.InfoTemplate(parcels_title_content, parcels_content);
            detailGraphic.setInfoTemplate(infoTemplate);
            dojo.byId("adjoiners-details-content").innerHTML = detailGraphic.getContent(); ;
            map.infoWindow.hide();
            if (detailGraphic.geometry != null) {
                // Create template for the info window
                try {

                    // this is a work around for problem with dojo shape is null when shape is not in the current extent
                    //  problem occurred at v1.4
                    zoomAfterLoadEvntHandle = dojo.connect(map, "onExtentChange", function() {
//                        try {
//                            detailGraphic.setSymbol(parcelHighlightSymbol);
//                        } catch (Error) {
//                            console.debug("Still getting the error...Try Again?");
//                        }
                        dojo.disconnect(zoomAfterLoadEvntHandle);
                    });

                    //
                    zoomMap(detailGraphic.geometry.getExtent().expand(1.3));
                } catch (Error) {
                    console.debug("error");
                }
            }

            adjoiners_show("details");
        }
    }

    catch (Err) {
        console.debug(Err)
    }   

}

function zoomToAdjoiner(index) {

    try {
        
        var selectedGraphic = adjoinerGraphics.graphics[index];
        if (selectedGraphic != null) {
            zoomMap(selectedGraphic.geometry.getExtent().expand(1.3));
        }
    }
    catch (Err) {
        console.debug(Err)
    }

}

function zoomToAllAdjoiners() {

    try {
        var fullExt = esri.graphicsExtent(adjoinerGraphics.graphics);
        if (fullExt != null)
            map.setExtent(fullExt.expand(1.1));
    } catch (Error) {
        console.warn("An Error occurred in the application in routine 'zoomToSelected'", Error);
    }
}

function adjoiners_show(panel) {

    if (panel == "details") {
        dojo.style("adjoiners-details", { display: "block" });
        dojo.style("adjoiners-report", { display: "none" });

    } else {
        dojo.style("adjoiners-details", { display: "none" });
        dojo.style("adjoiners-report", { display: "block" });
    }
}


function printAdjoiners() {

    var pid = getFieldValue(adjoinerFeature, fields.keyfield);

    var state = {
        map: getMapState(map),
        height: 600,
        width: 600,
        pid: pid,
        searchURL: parcelSearchLayerURL,
        reportType:"adjoiners",
        scale: getMapScale(map.extent)
    }

    var iframeDocument = dojo.isIE ? printingHiddenFrame.contentWindow.document : printingHiddenFrame.contentDocument;
    iframeDocument.getElementById("appState").value = dojo.toJson(state);
    iframeDocument.getElementById("form").submit();
}

function exportAdjoiners() {
    dijits.custom.Parcels.Export(adjoinerFeatures);
}

//////////var adjoinersStore;
//////////var adjoinerFeature;
//////////var adjoinerGraphics;
//////////var labelPointGraphics;
//////////var closeAdjoinersHandle;
//////////var mapRedrawHandle;






//////////function adjoinerReport_step1(pid) {

//////////    // Set up query tasks
//////////    var queryTask = new esri.tasks.QueryTask(baseMapLayerUrl + "/" + parcels_layerID);
//////////    // Set up query for the hazardous parcel
//////////    var query = new esri.tasks.Query();
//////////    query.where = fields.PID + " = '" + pid + "'";

//////////    query.outFields = parcels_return_fields;
//////////    query.returnGeometry = true;

//////////    //Execute task and call showResults on completion
//////////    queryTask.execute(query, adjoinerReport_step2);

//////////}

//////////function adjoinerReport_step2(results) {
//////////    if (results.features.length == 0) {
//////////        dojo.byId("info").innerHTML = "<p>Sorry, but your query return no results from the database</p>"
//////////        showPanel("info");
//////////        return;
//////////    }

//////////    if (results.features.length == 1) {
//////////        adjoinerFeature = results.features[0]
//////////        doAdjoinerQuery(adjoinerFeature.geometry);
//////////    }
//////////    else {
//////////        dojo.byId("status").innerHTML = "<p>More than one Parcel returned from the results</p>"
//////////        dojo.style("reportDiv", { display: "none" });
//////////    }
//////////}

//////////function doAdjoinerQuery(geometry) {

//////////        // Set up query tasks
//////////        queryTaskSurroundingParcels = new esri.tasks.QueryTask(baseMapLayerUrl + "/" + parcels_layerID);

//////////        // Reference proxy page
//////////        esriConfig.defaults.io.proxyUrl = proxyPage;
//////////        esriConfig.defaults.io.alwaysUseProxy = false;

//////////        this.orginalGeometry = geometry;

//////////        // Set up query for surrounding parcels
//////////        querySurroundingParcels = new esri.tasks.Query();
//////////        querySurroundingParcels.outFields = parcels_return_fields;
//////////        querySurroundingParcels.returnGeometry = true;
//////////        querySurroundingParcels.geometry = geometry;
//////////        querySurroundingParcels.spatialRelationship = esri.tasks.Query.SPATIAL_REL_TOUCHES;
//////////        queryTaskSurroundingParcels.execute(querySurroundingParcels, adjoiners_onComplete);

//////////}

//////////function adjoiners_onComplete(results) {

//////////    console.debug("adjoiner complete");
//////////    var s = [];
//////////    //createMapAddLayers();

//////////    // highlight symbol
//////////    var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID,
//////////                  new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASH,
//////////                  new dojo.Color([255, 0, 0]), 3), new dojo.Color([20, 150, 150, 0.50]));

//////////    var aPin = adjoinerFeature.attributes["CYPAR"];
//////////    var o1 = adjoinerFeature.attributes["OWNER"];
//////////    var o2 = adjoinerFeature.attributes["BOOK_PAGE"];

//////////    s.push("<div style=\"margin:20px\">")


//////////    s.push("<table width=\"100%\"><tr><td>Property Address:</td><td colspan=\"3\">" + getGraphicAttribute(adjoinerFeature, "SITUS_ADDX") + "</td</tr>");
//////////    s.push("<tr><td valign=\"top\">PIN: " + "</td><td valign=\"top\">" + aPin + "</td>");
//////////    s.push("<td valign=\"top\">Owner: " + "</td><td><div>" + o1 + "</div>");
//////////    s.push("</td></tr>");
//////////    s.push("</table>");

//////////    s.push("</div>")


//////////    adjoinerGraphics = [];

//////////    labelPointGraphics = [];

//////////    // write out the header rows
//////////    s.push("<div>");
//////////    s.push("<table cellspacing=\"1\" cellpadding=\"2\" border=\"0\" width=\"100%\">");
//////////    s.push("<tr><td>&nbsp;</td><td>Parcel ID</td><td>Owner</td><td>Deed</td></tr>");

//////////    // Add result features to map and table
//////////    var j = 0;
//////////    for (var i = 0, il = results.features.length; i < il; i++) {

//////////        //console.debug("here " + i);
//////////        var pin = results.features[i].attributes["CYPAR"];
//////////        var owner = results.features[i].attributes["OWNER"];
//////////        var deed = results.features[i].attributes["BOOK_PAGE"];

//////////        var cssClass = "aj";
//////////        //        if (i % 2 == 0)
//////////        //            cssClass = "aj-a";

//////////        var markerNum = i + 1
//////////        var markerimg = "images/bullets/bullet_" + markerNum + ".png"
//////////        s.push("<tr class='" + cssClass + "'><td><img src='" + markerimg + "' alt=\"" + markerNum + "\"/></td><td>" + pin + "</td><td>" + owner + "</td><td>" + deed + "</td></tr>");

//////////        //console.debug("cursor: " + i);
//////////        var curFeature = results.features[i];
//////////        var graphic = curFeature;
//////////        graphic.attributes

//////////        //Add result feature to map
//////////        graphic.setSymbol(symbol);

//////////        adjoinerGraphics.push(graphic);


//////////        // highlight symbol
//////////        var aSymbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID,
//////////                  new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASH,
//////////                  new dojo.Color([255, 0, 0]), 3), new dojo.Color([255, 100, 200, 0.50]));

//////////        adjoinerFeature.setSymbol(aSymbol);
//////////        adjoinerGraphics.push(adjoinerFeature);

//////////        // get center
//////////        var fExtent = graphic.geometry.getExtent();
//////////        var centerPt = fExtent.getCenter();

//////////        // add the point to the map
//////////        var mSym = new esri.symbol.PictureMarkerSymbol(markerimg, 16, 16);
//////////        var gPt = new esri.Graphic(centerPt, mSym, null, null);
//////////        labelPointGraphics.push(gPt);


//////////    }

//////////    s.push("</table></div>");

//////////    var aHTML = s.join("");

//////////    //zoomToAdjoiners();


//////////    // put the report into the report DOM
//////////    dojo.byId("report").innerHTML = aHTML;

//////////    // add the adjoiner feature in a new symbol

//////////}


//////////function zoomToAdjoiners() {

//////////    var a = adjoinerGraphics;

//////////    var fullExt;
//////////    if (a != null) {
//////////        for (var i = 0, il = a.length; i < il; i++) {
//////////            var e = a[i].geometry.getExtent();
//////////            if (fullExt == null)
//////////                fullExt = e;
//////////            else
//////////                fullExt = fullExt.union(e);

//////////            //map.graphics.add(a[i]);
//////////        }

//////////        if (fullExt != null)
//////////        //map.setExtent(fullExt);

//////////            xmin = fullExt.xmin;
//////////        ymin = fullExt.ymin;
//////////        xmax = fullExt.xmax;
//////////        ymin = fullExt.ymax;
//////////        initialExtent = new esri.geometry.Extent(xmin, ymin, xmax, ymax, new esri.SpatialReference({ wkid: 2264 }));

//////////        createMapAddLayers();

//////////        if (map.loaded) {
//////////            addGraphics_AfterLoad();
//////////        } else { dojo.connect(map, "onLoad", addGraphics_AfterLoad); }
//////////    }




//////////}
//////////function addGraphics_AfterLoad() {

//////////    var a = adjoinerGraphics;

//////////    for (var i = 0, il = a.length; i < il; i++) {
//////////        map.graphics.add(a[i]);
//////////        console.debug(i);
//////////    }


//////////    for (var i = 0, il = labelPointGraphics.length; i < il; i++) {
//////////        map.graphics.add(labelPointGraphics[i]);

//////////    }
//////////}