dojo.require("dijit.Dialog");
dojo.require("dojo.parser");
dojo.require("esri.map");
dojo.require("esri.dijit.Scalebar");
dojo.require("esri.tasks.query");
dojo.require("esri.tasks.find");
dojo.require("esri.tasks.identify");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.layout.AccordionContainer");
dojo.require("dijit.TitlePane");
dojo.require("esri.layers.graphics");
dojo.require("esri.tasks.geometry");

var map, LatLon;
var Aerial, Aerial_print, Streets, Streets_print, Layers, Parcels, Zoning, Zoning_print, RoadNames;
var queryTask1, queryTask2, queryTask3, query;
var identifyTask, identifyParams, identifyParams2, symbol;
var gsvc, navToolbar;
var gsvc, params, zoom = 0;
var graphicLayer1, graphicLayer2;
var printMapURL, imageList;
var visible = [];

function init() {
    esri.config.defaults.io.proxyUrl = "../proxy.ashx";
    esri.config.defaults.io.alwaysUseProxy = false;
    map = new esri.Map("map", { nav: true });
    dojo.connect(map, "onLoad", showLoading);
    dojo.connect(map, "onLoad", hideLoading_printImage);
    var streetLayer = "http://ags.wingis.org/ArcGIS/rest/services/1_Street/MapServer";
    var aerialLayer = "http://ags.wingis.org/ArcGIS/rest/services/1_Aerials/MapServer";
    var zoningLayer = "http://ags.wingis.org/ArcGIS/rest/services/1_Zoning_a/MapServer";
    Streets = new esri.layers.ArcGISTiledMapServiceLayer(streetLayer, { id: "Streets", visible: false });
    Streets_print = new esri.layers.ArcGISDynamicMapServiceLayer(streetLayer, { id: "Streets_p", visible: false });
    map.addLayer(Streets);
    Aerial = new esri.layers.ArcGISTiledMapServiceLayer(aerialLayer, { id: "Aerial", visible: true });
    Aerial_print = new esri.layers.ArcGISDynamicMapServiceLayer(aerialLayer, { id: "Aerial_p", visible: false });
    map.addLayer(Aerial);
    Zoning = new esri.layers.ArcGISTiledMapServiceLayer(zoningLayer, { id: "Zoning", visible: false, "opacity": 0.5 });
    Zoning_print = new esri.layers.ArcGISDynamicMapServiceLayer(zoningLayer, { id: "Zoning_p", visible: true, "opacity": 0.5 });
    map.addLayer(Zoning);
    Layers = new esri.layers.ArcGISDynamicMapServiceLayer("http://ags.wingis.org/ArcGIS/rest/services/1_Layers/MapServer", { id: "Layers" });
    map.addLayer(Layers);
    Parcels = new esri.layers.ArcGISDynamicMapServiceLayer("http://ags.wingis.org/ArcGIS/rest/services/1_Parcels/MapServer", { id: "Parcels", visible: false });
    map.addLayer(Parcels);
    RoadNames = new esri.layers.ArcGISDynamicMapServiceLayer("http://ags.wingis.org/ArcGIS/rest/services/1_RoadNames/MapServer", { id: "RoadNames", visible: false });
    map.addLayer(RoadNames);

    dojo.connect(map, "onLoad", hideLoading);
    navToolbar = new esri.toolbars.Navigation(map);
    dojo.connect(map, "onZoomStart", showLoading);
    dojo.connect(map, "onZoomEnd", hideLoading);
    dojo.connect(map, "onPanStart", showLoading);
    dojo.connect(map, "onPanEnd", hideLoading);
    dojo.connect(map, "onLoad", identParcels);
    dojo.connect(map, "onUpdate", hideLoading);
    var timer;
    dojo.connect(map, 'onLoad', function (theMap) {
        var scalebar = new esri.dijit.Scalebar({
            map: map,
            scalebarUnit: 'english'
        });
        dojo.connect(window, "onresize", function () {
            clearTimeout(timer);
            timer = setTimeout(function () { console.log('resizing map...'); map.resize(); }, 500);
        });
    });

    queryTask1 = new esri.tasks.QueryTask("http://ags.wingis.org/ArcGIS/rest/services/1_Layers/MapServer/1");
    queryTask2 = new esri.tasks.QueryTask("http://ags.wingis.org/ArcGIS/rest/services/1_Layers/MapServer/2");
    //build query filter
    query = new esri.tasks.Query();
    query.returnGeometry = true;
    query.outFields = ["*"];
    gsvc = new esri.tasks.GeometryService("http://ags.wingis.org/arcgis/rest/services/Geometry/GeometryServer");
    dojo.connect(map, "onClick", projectToLatLong);

    dojo.connect(map, 'onLoad', function (map) {
        graphicLayer1 = new esri.layers.GraphicsLayer();
        map.addLayer(graphicLayer1);
        graphicLayer2 = new esri.layers.GraphicsLayer();
        map.addLayer(graphicLayer2);
    });

    dojo.connect(map, "onLoad", fromRaar);
}
//********************************* MISC FUNCTIONS *********************************
function showLoading() {
    document.getElementById('loading').style.visibility = 'visible';
}

function hideLoading() {
    document.getElementById('loading').style.visibility = 'hidden';
}

function showLoading_printImage() {
    document.getElementById('loading_printImage').style.visibility = 'visible';
}

function hideLoading_printImage() {
    document.getElementById('loading_printImage').style.visibility = 'hidden';
}

function Help(type) {
    var helpContent = "";
    if (type == 1) {
        dijit.byId("dialogOne").show();
        helpContent = "<b>Property Search</b><br />";
        helpContent += "When searching for addresses, don't include street directionals as well as street suffixes. For example, 404 W. Elm St. would be <b>404 Elm</b>.";
        helpContent += "<br /><br />If a property is on the 4400 block of Main St., simply type <b>44 Main</b>. All addresses with 44 Main will appear in the search results (4401, 4402, 4403, etc.)";
        dojo.byId("HelpWindow").innerHTML = helpContent;
    }
    if (type == 2) {
        dijit.byId("dialogOne").show();
        helpContent = "<b>Print Options</b><br />";
        helpContent += "Use the first <b>Print</b> option to create a printable page containing an image of the property as well as listing the parcel details.<br />";
        helpContent += "<br />Use the second <b>Create Image</b> button to create an image out of the current map, including any markup or highlighted parcels.";
        helpContent += "<br /><br />*The image created is in 'png' format. Internet Explorer has issues printing png images. Simply right click on the image to save it to your local";
        helpContent += " machine. You should then be able to print with no issues.";
        dojo.byId("HelpWindow").innerHTML = helpContent;
    }
}

//===================================== MAP LAYERS =====================================

function toggleBasemap(layerID) {
    var basemapAerial = map.getLayer('Aerial');
    var basemapStreets = map.getLayer('Streets');
    if (layerID == 'Aerial') {
        basemapAerial.show();
        basemapStreets.hide();
    }
    if (layerID == 'Streets') {
        basemapAerial.hide();
        basemapStreets.show();
    }
}

function toggleParcels() {
    var ParcelLayer = map.getLayer('Parcels');
    if (ParcelLayer.visible) {
        ParcelLayer.hide();
    }
    else {
        ParcelLayer.show();
    }
}

function toggleZoning() {
    var ZoningLayer = map.getLayer('Zoning');
    if (ZoningLayer.visible) {
        ZoningLayer.hide();
    }
    else {
        ZoningLayer.show();
    }
}

function toggleRoadNames() {
    var RoadNamesLayer = map.getLayer('RoadNames');
    if (RoadNamesLayer.visible) {
        RoadNamesLayer.hide();
    }
    else {
        RoadNamesLayer.show();
    }
}

//********************************* QUERY AND ZOOM FUNCTIONS *********************************
function zoomToParcelQuery(searchString, myzoom) {
    if (myzoom == 1) {
        zoom = 1;
        query.where = "PIN = '" + searchString + "'";
        queryTask1.execute(query, showFindResults);
    }
    else {
        zoom = 0;
        query.where = "PIN = '" + searchString + "'";
        queryTask1.execute(query, showFindResults);
    }
}

function zoomToParcelQuery_Boone(searchString, myzoom) {
    if (myzoom == 1) {
        zoom = 1;
        query.where = "PIN = '" + searchString + "'";
        queryTask2.execute(query, showFindResults_b);
    }
    else {
        zoom = 0;
        query.where = "PIN = '" + searchString + "'";
        queryTask2.execute(query, showFindResults_b);
    }
}

function showFindResults(results) {
    graphicLayer1.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 PinNumber = results.features[i].attributes['PIN'];
        if (PinNumber == null) {
            document.forms["form1"].elements["text1"].value = 'No Pin Selected';
            document.forms["form1"].elements["text2"].value = 'Winnebago County';
        }
        else {
            document.forms["form1"].elements["text1"].value = PinNumber;
            document.forms["form1"].elements["text2"].value = 'Winnebago County';
        }
        var featureAttributes = results.features[i].attributes;
        var graphic = results.features[i];
        graphic.setSymbol(symbol);
        graphicLayer1.add(graphic);
        var selectedTaxLot = results.features[i].geometry.getExtent();
    }
    if (zoom == 0) {
        var taxLotExtent = selectedTaxLot;
        zoomToParcel(taxLotExtent);
    }
}

function showFindResults_b(results) {
    graphicLayer1.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 PinNumber = results.features[i].attributes['pin'];
        if (PinNumber == null) {
            document.forms["form1"].elements["text1"].value = 'No Pin Selected';
            document.forms["form1"].elements["text2"].value = 'Boone County';
        }
        else {
            document.forms["form1"].elements["text1"].value = PinNumber;
            document.forms["form1"].elements["text2"].value = 'Boone County';
        }
        var featureAttributes = results.features[i].attributes;
        var graphic = results.features[i];
        graphic.setSymbol(symbol);
        graphicLayer1.add(graphic);
        var selectedTaxLot = results.features[i].geometry.getExtent();
    }
    if (zoom == 0) {
        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 - 200;
    newZoomExtent.ymin = extent.ymin - 200;
    newZoomExtent.xmax = extent.xmax + 200;
    newZoomExtent.ymax = extent.ymax + 200;
    map.setExtent(newZoomExtent);
}

function fromRaar() {
    if (raarPin != "") {
        if (raarCounty == "winn") {
            fromRaar_query(raarPin);
        }
        if (raarCounty == "boone") {
            fromRaar_query_boone(raarPin);
        }

    }
}

function fromRaar_query(raarPin) {
    query.where = "PIN = '" + raarPin + "'";
    queryTask1.execute(query, fromRaar_zoom);
    document.forms["form1"].elements["text1"].value = raarPin;
    document.forms["form1"].elements["text2"].value = 'Winnebago County';

}

function fromRaar_zoom(results) {
    var s = "";
    var l = "";
    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);
        for (att in featureAttributes) {
            s = s + "<b>" + att + ":</b>  " + featureAttributes[att] + "<br />";
        }
        var extent = results.features[i].geometry.getExtent();
        var newZoomExtent = new esri.geometry.Extent();
        newZoomExtent.spatialReference = new esri.SpatialReference({ wkid: 3436 });
        newZoomExtent.xmin = extent.xmin - 200;
        newZoomExtent.ymin = extent.ymin - 200;
        newZoomExtent.xmax = extent.xmax + 200;
        newZoomExtent.ymax = extent.ymax + 200;
    }
    map.setExtent(newZoomExtent);
}

function fromRaar_query_boone(raarPin) {
    query.where = "PIN = '" + raarPin + "'";
    queryTask2.execute(query, showResults_123);
    document.forms["form1"].elements["text1"].value = raarPin;
    document.forms["form1"].elements["text2"].value = 'Boone County';
}

function showResults_123(results) {
    for (var i = 0, il = results.features.length; i < il; i++) {
        zoomToParcelQuery_123(results.features[i].attributes['OBJECTID']);
    }
}

function zoomToParcelQuery_123(Oid) {
    query.where = "OBJECTID = " + Oid + "";
    queryTask2.execute(query, showFindResults_123);
}

function showFindResults_123(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_123(taxLotExtent);
}

function zoomToParcel_123(extent) {
    map.setExtent(extent);
}

//======================================== IDENTIFY FUNCTION ========================================
function identParcels() {
    identConnect = dojo.connect(map, "onClick", doIdentify_id);
    var serviceID = "Layers"; //Must Be Name of Map Layer In TOC
    var inputs = dojo.query("." + serviceID + "TOC_2"), input;
    identifyTask = new esri.tasks.IdentifyTask("http://ags.wingis.org/ArcGIS/rest/services/1_Layers/MapServer");
    identifyParams = new esri.tasks.IdentifyParameters();
    identifyParams.tolerance = 3;
    identifyParams.returnGeometry = true;
    identifyParams.layerIds = [1];
    identifyParams.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_ALL;

    identifyParams2 = new esri.tasks.IdentifyParameters();
    identifyParams2.tolerance = 3;
    identifyParams2.returnGeometry = true;
    identifyParams2.layerIds = [2];
    identifyParams2.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_ALL;

    map.infoWindow.resize(275, 195);
    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_id(evt) {
    identifyParams.geometry = evt.mapPoint;
    identifyParams.mapExtent = map.extent;
    identifyParams2.geometry = evt.mapPoint;
    identifyParams2.mapExtent = map.extent;
    identifyTask.execute(identifyParams, function (idResults) {
        if (idResults == "") {
            identifyTask.execute(identifyParams2, function (idResults2) { addToMap_Boone(idResults2, evt); });
            map.infoWindow.show(evt.screenPoint, map.getInfoWindowAnchor(evt.screenPoint));
        }
        else {
            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'><a href='../parcelDetails/pdGeneral.aspx?Pin=" + layerResults.features[i].attributes['PIN'] + "' target='pdFrame' onclick=\"javascript:zoomToParcelQuery('" + layerResults.features[i].attributes['PIN'] + "',1);\">Select</a>";
        content += "&nbsp; - &nbsp; <a href='../parcelDetails/pdGeneral.aspx?Pin=" + layerResults.features[i].attributes['PIN'] + "' target='pdFrame' onclick=\"javascript:zoomToParcelQuery('" + layerResults.features[i].attributes['PIN'] + "',0);\">Zoom To</a><td><tr>";
        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'] + "</td></tr>";
        content += "<tr><td colspan='2'>Sq. Feet: " + (layerResults.features[i].attributes['Shape.area'] / 1).toFixed(0) + " &nbsp; - &nbsp;  Acres: " + (layerResults.features[i].attributes['Shape.area'] / 43560).toFixed(2) + "</td></tr>";
        content += "<tr><td colspan='2'>County: Winnebago</td></tr>";
        content += "<tr><td colspan='2'><hr size='1' /></td></tr>";
    }
    content += "</table>";
    map.infoWindow.setContent(content + LatLon);
}

function addToMap_Boone(idResults, evt) {
    layer0results = { displayFieldName: null, features: [] };
    for (var i = 0, il = idResults.length; i < il; i++) {
        var idResult = idResults[i];
        if (idResult.layerId === 2) {
            if (!layer0results.displayFieldName) { layer0results.displayFieldName = idResult.displayFieldName };
            layer0results.features.push(idResult.feature);
        }
    }
    layerTabContent_Boone(layer0results, "layer0results");
}

function layerTabContent_Boone(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'><a href='../parcelDetails/pdGeneral_Boone.aspx?ObjectID=" + layerResults.features[i].attributes['OBJECTID'] + "&Pin=" + layerResults.features[i].attributes['PIN'] + "' target='pdFrame' onclick=\"javascript:zoomToParcelQuery_Boone('" + layerResults.features[i].attributes['PIN'] + "',1);\">Select</a>";
        content += "- &nbsp - <a href='../parcelDetails/pdGeneral_Boone.aspx?ObjectID=" + layerResults.features[i].attributes['OBJECTID'] + "&Pin=" + layerResults.features[i].attributes['PIN'] + "' target='pdFrame' onclick=\"javascript:zoomToParcelQuery_Boone('" + layerResults.features[i].attributes['PIN'] + "',0);\">Zoom To</a></td></tr>";
        content += "<tr><td colspan='2'>" + layerResults.features[i].attributes['Full Street Address'] + "</td></tr>";
        content += "<tr><td colspan='2'>Pin &nbsp;" + layerResults.features[i].attributes['PWD'] + "</td></tr>";
        content += "<tr><td colspan='2'>Sq. Feet: " + (layerResults.features[i].attributes['Shape.area'] / 1).toFixed(0) + " &nbsp; - &nbsp;  Acres: " + (layerResults.features[i].attributes['Shape.area'] / 43560).toFixed(2) + "</td></tr>";
        content += "<tr><td colspan='2'>County: Boone</td></tr>";
        content += "<tr><td colspan='2'><hr size='1' /></td></tr>";
    }
    content += "</table>";
    map.infoWindow.setContent(content + LatLon);
}

function clearAll(feature) {
    map.graphics.clear();
    dojo.byId("idResults").innerHTML = "";
}
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) {
    var outSR = new esri.SpatialReference({ wkid: 4326 });
    var point = evt.mapPoint;
    gsvc.project([point], outSR, function (projectedPoints) {
        pt = projectedPoints[0];
        LatLon = "<table border='0'><tr><td>Latitude = " + pt.y.toFixed(6) + "</td></tr><tr><td>Longitude = " + pt.x.toFixed(6) + "</td></tr>";
        LatLon += "<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></table>";
    });
}

//===================================== PRINTING =====================================
function exportMap() {
    showLoading_printImage();
    var mapExtent = map.extent;
    var mapWidth = map.width; //1240;
    var mapHeight = map.height;  //600; 
    dojo.byId("BlendedImage").innerHTML = "";
    var imgParams = new esri.layers.ImageParameters();
    imgParams.bbox = mapExtent;
    imgParams.width = mapWidth;
    imgParams.height = mapHeight;
    imgParams.transparent = false; //base map not transparent
    var basemap;
    if (Aerial.visible) {
        basemap = Aerial_print;
    }
    else {
        basemap = Streets_print;
    }
    basemap.exportMapImage(imgParams, function (mapImage) {
        imageList = mapImage.href + ";" + basemap.opacity;
        var imgParams = new esri.layers.ImageParameters();
        imgParams.bbox = mapExtent;
        imgParams.width = mapWidth;
        imgParams.height = mapHeight;
        imgParams.transparent = true; //top map transparent must set to be true
        Zoning_print.exportMapImage(imgParams, function (mapImage) {
            console.log("Image url returned:" + mapImage.href);
            if (Zoning.visible) {
                imageList += "$" + mapImage.href + ";" + Zoning_print.opacity;
            }
            Parcels.exportMapImage(imgParams, function (mapImage) {
                console.log("Image url returned:" + mapImage.href);
                if (Parcels.visible) {
                    imageList += "$" + mapImage.href + ";" + Parcels.opacity;
                }
                RoadNames.exportMapImage(imgParams, function (mapImage) {
                    console.log("Image url returned:" + mapImage.href);
                    if (RoadNames.visible) {
                        imageList += "$" + mapImage.href + ";" + RoadNames.opacity;
                    }
                    imageList += "|" + GetScreenGraphic();
                    SimpleService.BlendImageList(imageList, OnComplete, OnTimeOut, OnError);
                });
            });
        });
    });
}

function GetScreenGraphic() {
    var graphicList = "";
    var graphics = (graphicLayer1.graphics).concat(graphicLayer2.graphics).concat(map.graphics.graphics);
    var graphicType;
    var graphicSymbol;
    var graphicText = "";
    var style = "";
    for (var i = 0; i < graphics.length; i++) {
        var xy, point, screenPoint;
        var type = graphics[i].geometry.type;
        if (type === "point" || type === "multipoint") {
            graphicSymbol = graphics[i].symbol.type + "_" + graphics[i].symbol.style;
            style = graphics[i].symbol.color.r + "_" + graphics[i].symbol.color.g + "_" + graphics[i].symbol.color.b + "_" + dojo.number.round(graphics[i].symbol.color.a, 1);
            graphicText = "";
            switch (graphicSymbol) {
                case "simplemarkersymbol_circle":
                    graphicType = "CIRCLE";
                    style += "_" + dojo.number.round(graphics[i].symbol.size, 0) + "_" + dojo.number.round(graphics[i].symbol.outline.width, 0);
                    break;
                case "simplemarkersymbol_square":
                    graphicType = "SQUARE";
                    style += "_" + dojo.number.round(graphics[i].symbol.size, 0) + "_" + dojo.number.round(graphics[i].symbol.outline.width, 0);
                    break;
                case "simplemarkersymbol_diamond":
                    graphicType = "DIAMOND";
                    style += "_" + dojo.number.round(graphics[i].symbol.size, 0) + "_" + dojo.number.round(graphics[i].symbol.outline.width, 0);
                    break;
                case "simplemarkersymbol_x":
                    graphicType = "CROSS";
                    break;
                case "textsymbol_undefined":
                    graphicType = "CIRCLE";
                    graphicText = graphics[i].symbol.text;
                    break;
                case "textsymbol_esriTS":
                    graphicType = "CIRCLE";
                    graphicText = graphics[i].symbol.text;
                    break;
                case "picturemarkersymbol_undefined":
                    graphicType = "CIRCLE";
                    graphicText = graphics[i].symbol.width + "-" + graphics[i].symbol.height; style = graphics[i].symbol.angle + "-picturemarkerurl-" + graphics[i].symbol.url;
                    break;
                case "picturemarkersymbol_esriSMS":
                    graphicType = "CIRCLE";
                    graphicText = graphics[i].symbol.width + "-" + graphics[i].symbol.height; style = graphics[i].symbol.angle + "-picturemarkerurl-" + graphics[i].symbol.url;
                    break;
            }
            graphicList += graphicType + ";" + style + ";";
            point = new esri.geometry.Point(graphics[i].geometry.x, graphics[i].geometry.y, map.spatialReference);
            screenPoint = map.toScreen(point);
            graphicList += graphicText + ";" + screenPoint.x + "," + screenPoint.y + "$";
        }
        else if (type === "line" || type === "polyline") {
            graphicSymbol = (graphics[i].symbol.type + "_" + graphics[i].symbol.style + "_" + graphics[i].symbol.color.r + "_" + graphics[i].symbol.color.g + "_" + graphics[i].symbol.color.b + "_" + dojo.number.round(graphics[i].symbol.color.a, 1) + "_" + dojo.number.round(graphics[i].symbol.width, 0));
            graphicText = "";
            style = "";
            if (graphicSymbol.indexOf("simplelinesymbol_solid_") >= 0) { graphicType = "LINE"; style = graphicSymbol.replace("simplelinesymbol_solid_", ""); }
            graphicList += graphicType + ";" + style + ";";
            for (var p = 0; p < graphics[i].geometry.paths.length; p++) {
                for (var j = 0; j < graphics[i].geometry.paths[p].length; j++) {
                    xy = graphics[i].geometry.paths[p][j];
                    point = new esri.geometry.Point(parseFloat(xy[0]), parseFloat(xy[1]), map.spatialReference);
                    screenPoint = map.toScreen(point);
                    graphicList += screenPoint.x + "," + screenPoint.y + "%";
                }
            }
            graphicList = graphicList.substring(0, graphicList.length - 1);
            graphicList += "$";
        }
        else if (type === "polygon") {
            graphicSymbol = (graphics[i].symbol.type + "_" + graphics[i].symbol.outline.style + "_" + graphics[i].symbol.outline.color.r + "_" + graphics[i].symbol.outline.color.g + "_" + graphics[i].symbol.outline.color.b);
            graphicText = "";
            style = "";
            if (graphics[i].symbol._fill != null) {
                graphicSymbol += "_" + graphics[i].symbol._fill.r + "_" + graphics[i].symbol._fill.g + "_" + graphics[i].symbol._fill.b + "_" + dojo.number.round(graphics[i].symbol._fill.a, 1);
                //Format:simplefillsymbol_solid_255_0_0_255_255_0_0.5 (outline style + fill rgbr)
                if (graphicSymbol.indexOf("simplefillsymbol_solid_") >= 0) { graphicType = "FILLPOLYGON"; style = graphicSymbol.replace("simplefillsymbol_solid_", ""); }
            }
            else {//Polygon without fill
                if (graphicSymbol.indexOf("simplefillsymbol_solid_") >= 0) { graphicType = "HOLLOWPOLYGON"; style = graphicSymbol.replace("simplefillsymbol_solid_", ""); }

                else if (graphicSymbol == "simplefillsymbol_dashdot_") { graphicType = "DASHPOLYGON"; style = graphicSymbol.replace("simplefillsymbol_dashdot_", ""); }
            }
            graphicList += graphicType + ";" + style + ";";
            var uniqueList = [];
            for (var k = 0; k < graphics[i].geometry.rings.length; k++) {
                for (var l = 0; l < graphics[i].geometry.rings[k].length; l++) {
                    xy = graphics[i].geometry.rings[k][l];
                    //prevent drawing from 1st to last point
                    if (IsInList(uniqueList, xy[0] + "," + xy[1]) == true) {
                        graphicList = graphicList.substring(0, graphicList.length - 1);
                        graphicList += "$" + graphicType + ";" + style + ";";
                        uniqueList = [];
                    }
                    else {
                        uniqueList.push(xy[0] + "," + xy[1]);
                        point = new esri.geometry.Point(parseFloat(xy[0]), parseFloat(xy[1]), map.spatialReference);
                        screenPoint = map.toScreen(point);
                        graphicList += screenPoint.x + "," + screenPoint.y + "%";
                    }
                }
            }
            graphicList = graphicList.substring(0, graphicList.length - 1);
            graphicList += "$";
        }
    }
    graphicList = graphicList.substring(0, graphicList.length - 1);
    return graphicList;
}

function IsInList(list, item) {
    for (var i = 0; i < list.length; i++) {
        if (list[i] == item) {
            return true;
        }
    }
    return false;
}

function OnComplete(arg) {
    hideLoading_printImage();
    dojo.byId("BlendedImage").innerHTML = "<a href='" + arg + "' target='_blank' >View image</a>";
}

function OnTimeOut(arg) {
    alert("TimeOut encountered when calling map image.");
}

function OnError(arg) {
    alert("Error encountered when calling map image.");
}

function PrintwDetails() {
    var PinNo = document.forms["form1"].elements["text1"].value;
    if (document.forms["form1"].elements["text2"].value == "Boone County") {
        var mypage = "../PrintPage_Boone.aspx?Pin=" + PinNo;
    }
    else {
        var mypage = "../PrintPage.aspx?Pin=" + PinNo + "&DashPin=xxxx";
    }
    var myname = "exportmap"
    var settings = "scrollbars=yes,location=no,directories=no,status=yes,menubar=no,toolbar=no,resizable=yes";
    win = window.open(mypage, myname, settings);
    win.focus();
}

//================================================================================
dojo.addOnLoad(init);
