﻿var map;
var hidemap = null;
var index = 0;
var results = null;
var maxMapWidth = 1000;
var maxMapHeight = 575;
var geocodepoint = null;
var filtercrime = null;
var slDrawing = new VEShapeLayer();
var geocodepoint = null;
var shapeLayer = null;
var myGeomType = null;
var myCurrentShape = null;
var myPoints = new Array();
var myDistance = 0;
var tempShape = null;
var tempPoints = null;
var tempDistance = 0;
var myCirclePoints = null;
var tempCircle = null;
var i = 1;
var categories = "";
var icon = "";
var filterDateTo = "";
var filterDateFrom = "";
var bWidth = 0;
var bHeight = 0;
var slGeoRSS = new VEShapeLayer();
var latLong = null;
var moving = true;
  var numShapes = null;      
var currentTime;
var month;
var day;
var year;
var newdate;
var newdate1;


var currentShape = null;
var notOver = true;
 var count = 1;
  var s = null;

var GeoRSSAddToServiceId = 'Crime';
var GeoRSSLayerId = -1; 

var agisve_services = null; 
var agis_services = new Array();
        

        dojo.require("dijit.Toolbar");
        dojo.require("dijit.form.Button");
        dojo.require("dijit.layout.BorderContainer");
        dojo.require("dojo.parser");
        
        dojo.require("dijit.form.TextBox");

        dojo.require("esri.map");
        dojo.require("esri.tasks.geometry");
      dojo.require("esri.toolbars.draw");
      dojo.require("dojo.number");
      

      var geometryService= null;

        dojo.addOnLoad(init);

function mapStartUp()
{
  var layersLoaded = 0;  //varible to keep track of when all layers have been loaded.
        var loading = dojo.byId("loadingImg");  //loading image. id
    var centerat = new VELatLong(startLatitude, startLongitude);

    map = new VEMap('mymap');

    var mapOptions = new VEMapOptions();

    mapOptions.EnableBirdseye = false;

    map.LoadMap(centerat, startMapLevel, VEMapStyle.Road, false, VEMapMode.Mode2D, false, 0, mapOptions);

    map.ShowMessageBox = false;
    

if (moving = true)
{
 map.AttachEvent("onmouseover", mouseOverHandler);

  map.AttachEvent("onmouseout", mouseOutHandler);
  }
document.getElementById('Dropdown1').options[document.getElementById('Dropdown1').selectedIndex].value = '1';
document.getElementById('ctl00_MapAppHolder_DropDownList1').options[document.getElementById('ctl00_MapAppHolder_DropDownList1').selectedIndex].value = '0';
 document.getElementById('ctl00_MapAppHolder_DropDownList2').options[document.getElementById('ctl00_MapAppHolder_DropDownList2').selectedIndex].value = '0';
 document.getElementById('ctl00_MapAppHolder_DropDownList3').options[document.getElementById('ctl00_MapAppHolder_DropDownList3').selectedIndex].value = '0';
 document.getElementById('ctl00_MapAppHolder_DropDownList4').options[document.getElementById('ctl00_MapAppHolder_DropDownList4').selectedIndex].value = '0';  
  AdjustWebPage(); 
  window.onresize = AdjustWebPage;
 currentTime = new Date();
 month = currentTime.getMonth() + 1
 day = currentTime.getDate();
year = currentTime.getFullYear();
newdate = month + "/" + day + "/" + year;
newdate1 = month + "/" + "1" + "/" + year;
//newdate1 = "10" + "/" + "25" + "/" + year;

document.getElementById('Text2').value = newdate;
document.getElementById('Text1').value = newdate1;
document.getElementById('selMonth2').value = month;
document.getElementById('selDay2').value =  day;
document.getElementById('selYear2').value =  year;
document.getElementById('selMonth').value = month;
document.getElementById('selDay').value =  "1";
document.getElementById('selYear').value =  year;
 

}


function AdjustWebPage()

{

    browserSize();

    var mapwidth = bWidth-50;

    var mapheight = bHeight - 300;

 

document.getElementById('tools').style.left = 125 + 'px';



    

    if (mapheight>maxMapHeight)

    {

        document.getElementById('mapWrapper').style.height=mapheight+'px';
        

    }

    else

    {

        mapheight = maxMapHeight;

    }

    if (mapwidth>maxMapWidth)

    {

        document.getElementById('mapWrapper').style.width = mapwidth + 'px';

        document.getElementById('tools').style.left = (bWidth - 980) + 'px';  //adjust # to move query map, print, help and other buttons left or right
        

    }

    else

    {
        document.getElementById('tools').style.left = 100 + 'px';
        mapwidth = maxMapWidth;

    }

    document.getElementById('toolbar').style.width=(mapwidth+4)+'px';

   //document.getElementById('simpleTOC1').style.height=(mapheight-158)+'px';

    document.getElementById('SideBar').style.height = (mapheight - 158) + 'px';

    document.getElementById('footer').style.top = (mapheight + 50) + 'px';

    
    map.Resize(mapwidth,mapheight);

}

 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;
          }
        }

function init()
{
 dojo.connect(map, "onLoad", showLoading);
 dojo.connect(map, "onZoomStart", showLoading);
 dojo.connect(map, "onPanStart", showLoading);
 AddMap();
   
}
//document.getElementById('address').value,



 function ClearMap()
         {
            map.Clear();
         }
       
function GeocodeVE(theaddress) {
    var StringSearch = new String(theaddress)
    //alert(document.getElementById('searchaddress').value)
    //If Dallas not Supplied, then Add it
    theaddress = StringSearch.replace(/dallas/gi, '');
    theaddress = theaddress + ' , Dallas, Texas';
    //alert(theaddress);
    map.Find(null, theaddress, null, null, null, null, true, true, null, true, GetCoordinates);
}

function GetCoordinates(layer, resultsArray, places, hasMore, veErrorMessage) {
    //Delete any existing geocodepoint
    if (geocodepoint != null) {
        map.DeleteShape(geocodepoint);
        geocodepoint = null;
    }

    if (places != null) {
        //Places Were found
        findPlaceResults = places[0].LatLong;
        geocodepoint = new VEShape(VEShapeType.Pushpin, findPlaceResults);
        geocodepoint.SetTitle(places[0].Name);
        //geocodepoint.SetDescription(findPlaceResults.toString() + '<br>');
        document.getElementById('searchaddress').value = places[0].Name;
        map.AddShape(geocodepoint);
    }
    else {
        //No places were found
        alert("Address Not Found");
    }

    //End of Geocode Function
}


 
function AddMap() {

//var agisvecrime_services = new ESRI.ArcGIS.VE.ArcGISLayerFactory();
    //agisvecrime_services.CreateLayer(crimeMapURL, "Crimenew", GetMap);


    

    //var crimeMapServiceLayer = new esri.layers.ArcGISTiledMapServiceLayer(crimeMapURL, {id:'Crimenew'});
    //agis_services[0] = crimeMapServiceLayer;

    var dynamicMapServiceLayer = new esri.layers.ArcGISDynamicMapServiceLayer(dynamicUrl, {id:'Crime'});
    //hidemap.addLayer(dynamicMapServiceLayer);
    
    agis_services[0] = dynamicMapServiceLayer;

    
 dojo.connect(dynamicMapServiceLayer,'onLoad',this,'loadLegend');
  
    GetMap();
    
    
    //hidemap.addLayer(tiledMapServiceLayer);
    
    if(dynamicMapServiceLayer.layerInfos.length>0)
    {
    
       loadLegend();
   }
    
    //Enable Printing
    var printOpt = new VEPrintOptions(true);
     map.SetPrintOptions(printOpt);
     
    map.SetDisplayThreshold(10);

}


function getgeorsslayer() {
categories = "";


    if  (slGeoRSS != null)
    {
        slGeoRSS.DeleteAllShapes();

    }

    var view = map.GetMapView();
        var top = view.TopLeftLatLong.Latitude;
        var left = view.TopLeftLatLong.Longitude;
        var bottom = view.BottomRightLatLong.Latitude;
        var right = view.BottomRightLatLong.Longitude;
       
      //alert (category);
      

         filterDateFrom = document.getElementById('Text1').value;
         filterDateTo = document.getElementById('Text2').value;
        //alert(filterDateFrom);
       
      
        var url = "http://dallas.dfwmaps.com/Crimenew/handler3.ashx?LonLeft=" + left + "&LatTop=" + top + "&Lonright=" + right + "&Latbottom=" + bottom + "&filterdateFrom=" + filterDateFrom + "&filterdateTo=" + filterDateTo + "&t=<%=timer%>";
        
	//alert(url);
     
        dojo.forEach(
            GeoRSSCrimeFilters.Parameters,
            function (item)
            {
                
                if (item.Selected)
                {
                    if (categories!="")
                    {
                        categories +=", "
                    }
                    categories += item.Value;
                }
            }
        );
        url += "&Categories=" + categories;
        


     
    document.getElementById('SideBar').innerHTML=""; 
        var veLayerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS, url, slGeoRSS);
        
        map.ImportShapeLayerData(veLayerSpec, onFeedLoad, false);
    

}

function getgeorssclear() {
categories = "";

    if  (slGeoRSS != null)
    {
        slGeoRSS.DeleteAllShapes();
       

    }

    var view = map.GetMapView();
        var top = view.TopLeftLatLong.Latitude;
        var left = view.TopLeftLatLong.Longitude;
        var bottom = view.BottomRightLatLong.Latitude;
        var right = view.BottomRightLatLong.Longitude;
        
          var currentTime = new Date();
var month = currentTime.getMonth() + 1
var day = currentTime.getDate();
var year = currentTime.getFullYear();
newdate = month + "/" + day + "/" + year;
newdate2 = month + "/" + "1" + "/" + year;
document.getElementById('selMonth2').value = month;
document.getElementById('selDay2').value =  day;
document.getElementById('selYear2').value =  year;
//document.getElementById('Text2').value = newdate;
       
      //alert (category);
         //filterDateFrom = "09/01/2010";
         filterDateFrom = newdate2;
         filterDateTo = newdate;
        //alert(filterDateFrom);
       
      
        var url = "http://dallas.dfwmaps.com/Crimenew/handler3.ashx?LatTop=" + top + "&Lonright=" + right + "&Latbottom=" + bottom + "&filterdateFrom=" + filterDateFrom + "&filterdateTo=" + filterDateTo + "&t=<%=timer%>";
        

     
        dojo.forEach(
            GeoRSSCrimeFilters.Parameters,
            function (item)
            {
                
                if (item.Selected)
                {
                    if (categories!="")
                    {
                        categories +=", "
                    }
                    categories += item.Value;
                }
            }
        );
        url += "&categories=other+thefts"
    
 
 //alert (categories);
     
    
        var veLayerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS, url, slGeoRSS);
        
        map.ImportShapeLayerData(veLayerSpec, onFeedLoad, false);
   
}



function GetMap() {

   //tileSourceSpec.Opacity=0.35;
    //map.AddTileLayer(tileSourceSpec,showParcels);

 getgeorsslayer();
 map.AttachEvent("onchangeview", getgeorsslayer); 
 
          
}
function showcrime()
{

getgeorsslayer();
 slGeoRSS.Show();
}

function crimeclear()
{



 //document.getElementById('Text1').value = "09/01/2010";
 document.getElementById('Text1').value = newdate1;
 document.getElementById('Text2').value = newdate;
 
getgeorssclear();


}

function onFeedLoad(feed)
         {
         
     document.getElementById('SideBar').innerHTML=""; 
     numShapes = slGeoRSS.GetShapeCount();
    
     for(var i=0; i < numShapes; ++i)
    {
         s = slGeoRSS.GetShapeByIndex(i);
        
   count = s.GetMoreInfoURL();


if (count == '1')
{
moving = true;
 
 
var test = s.GetTitle();
//alert(test);

var pinHTML = "<div class='pinStyle'>{0}</div>";
//alert(test);
if (test == 'OTHER THEFTS') 
{
var pinHTML = "<div class='pinStyletheft'>{0}</div>";
}
 else if (test == 'BURGLARY-RESIDENCE') 
{
var pinHTML = "<div class='pinStyleburgularyresidence'>{0}</div>";
}
else if (test == 'BURGLARY-BUSINESS') 
{
var pinHTML = "<div class='pinStyleburgularyresidence'>{0}</div>";
}
else if (test == 'THEFT/BMV') 
{
var pinHTML = "<div class='pinStylebmv'>{0}</div>";
}
else if (test == 'AGG ASSAULT') 
{
var pinHTML = "<div class='pinStyleaggassault'>{0}</div>";
}
else if (test == 'BURGLARY-RESIDENCE') 
{
var pinHTML = "<div class='pinStyleburgularyresidence'>{0}</div>";
}
else
{
var pinHTML = "<div class='pinStyleautotheft'>{0}</div>";
}

                            
 

//s.SetCustomIcon(currentPinHTML);
s.SetCustomIcon(s.IconId);  
var currentPinHTML = pinHTML.replace('{0}',  '' );


//Build out sidebar
var itemHTML = '';

//var currentMarkerID = s.GetID();
////currentPinHTML = currentPinHTML.replace('<div ', '<div id=\'sideBarMarker_' + currentMarkerID+ '\' '); 
//currentPinHTML = currentPinHTML.replace('<div ', '<div id=\'sideBarMarker_' + currentMarkerID+ '\' '); 
//itemHTML += '<p><span onmouseover="mouseOverSidebarItem(\'' + s.GetID() + '\');" onmouseout="mouseOutSidebarItem(\'' + s.GetID() + '\');">';
//itemHTML += currentPinHTML;
////itemHTML += 'Marker # ' + i + '<br/>';
//itemHTML += s.GetTitle() + '<br/>';
//itemHTML += s.GetDescription()+ '<br/>';
////itemHTML += currentMarkerID + '<br/>';
//itemHTML += '_________________________<br/>';
//itemHTML += '</span><br/></p>';

//document.getElementById('SideBar').innerHTML += itemHTML;
          
} 
else
{
moving = false;
  
s.SetCustomIcon("<div class='pinStyle'><div class='text'>" + s.GetMoreInfoURL() + "</div></div>");

}
     }
}
function mouseOverSidebarItem(markerId){
        //Update pushpin
   
   
        currentShape = map.GetShapeByID(markerId);
        currentIcon = currentShape.GetCustomIcon();
        var test = currentShape.GetTitle();
        
    
        //currentShape.SetCustomIcon(currentIcon.replace('pinStyle', 'pinHoverStyle'));
        map.ShowInfoBox(currentShape);
        
        //Update side bar icon
        var sideBarIconId = 'sideBarMarker_' + currentShape.GetID();
       
        if (test == 'OTHER THEFTS') 
{
 document.getElementById(sideBarIconId).className = 'pinStyletheftsel';

}
else if (test == 'THEFT/BMV') 
{
 document.getElementById(sideBarIconId).className = 'pinStylebmvsel';

}
 else if (test == 'BURGLARY-RESIDENCE') 
{
document.getElementById(sideBarIconId).className = 'pinStyleburgularyresidencesel';

}
else if (test == 'AGG ASSAULT') 
{
document.getElementById(sideBarIconId).className = 'pinStyleaggassaultsel';

}
else if (test == 'BURGLARY-BUSINESS') 
{
document.getElementById(sideBarIconId).className = 'pinStyleburgularyresidencesel';

}

//else
//{
//document.getElementById(sideBarIconId).className = 'pinStyleautotheftsel';

//}
        
   
    }
     function mouseOutSidebarItem(markerId){
        //Update pushpin
      var test = currentShape.GetTitle();
     
        currentShape = map.GetShapeByID(markerId);
        currentIcon = currentShape.GetCustomIcon();
    
        //currentShape.SetCustomIcon(currentIcon.replace('pinHoverStyle', 'pinStyle'));
        map.HideInfoBox(currentShape);
        
        //Update side bar icon
        var sideBarIconId = 'sideBarMarker_' + currentShape.GetID();
      
        //document.getElementById(sideBarIconId).className = 'pinStyle';
        
         if (test == 'OTHER THEFTS') 
{
 document.getElementById(sideBarIconId).className = 'pinStyletheft';

}
else if (test == 'THEFT/BMV') 
{
 document.getElementById(sideBarIconId).className = 'pinStylebmv';

}
 else if (test == 'BURGLARY-RESIDENCE') 
{
document.getElementById(sideBarIconId).className = 'pinStyleburgularyresidence';

}
else if (test == 'AGG ASSAULT') 
{
document.getElementById(sideBarIconId).className = 'pinStyleaggassault';

}
else if (test == 'BURGLARY-BUSINESS') 
{
document.getElementById(sideBarIconId).className = 'pinStyleburgularyresidence';

}

//else
//{
//document.getElementById(sideBarIconId).className = 'pinStyleautotheft';

//}
    
    }
    function mouseOverHandler(e){
    //alert(e.elementID);
  
        if (e.elementID && notOver){
      

            mouseOverSidebarItem(e.elementID)
            
            notOver = false;
           
           
        }
    }
     function mouseOutHandler(e){
     
        if (e.elementID && !notOver){
            mouseOutSidebarItem(e.elementID)
            notOver = true;
        
    }
    }
//function CheckBox1Clicked(cb)
//{
//   if (cb.checked)
//   {
//   
//      slGeoRSS.Show();
//          
//   }
//   else
//   {
//      slGeoRSS.Hide();
//   }
//}

function loadLegend()
{

    var simpleTOC = dijit.byId('simpleTOC1');
    simpleTOC.init(map);    
    //addDynamicService(map,"Land Base",dynamicUrl,getTilePathLandBase, 1,showDynMap);
   addDynamicService(map,"Crime",dynamicUrl,getTilePathLandBase, 1,showDynMap);
    

    
}

function selectQueryTool()
{
    resetMapTools();
    if (document.getElementById('QueryMapText').className=='VEMapButtonSelected')
    {
        map.Clear();
    } 
    else
    {
        document.getElementById('QueryMapText').className='VEMapButtonSelected';
        document.getElementById('queryToolImg').className='QueryToolArrowSelected';
        document.getElementById("mymap").childNodes[0].style.cursor = "crosshair";
        map.AttachEvent("onmousedown", queryMap);
    }
}
function selectZoomInTool()
{
    resetMapTools();
    if (document.getElementById('ZoomInText').className=='VEMapButtonSelected')
    {
    } 
    else
    {
        document.getElementById('ZoomInText').className='VEMapButtonSelected';
        document.getElementById('ZoomInToolImg').className='QueryToolArrowSelected';
        document.getElementById("mymap").childNodes[0].style.cursor = "crosshair";
        map.AttachEvent("onmousedown", zoomInStart);
        map.AttachEvent("onmousemove", zoomInBox);
        map.AttachEvent("onmouseup", zoomInEnd);
        //map.AttachEvent("onmousedown", queryMap);
    }
}

function resetMapTools()
{
    document.getElementById('ZoomInText').className='VEMapButtonNonSelected';
    document.getElementById('ZoomInToolImg').className='QueryToolArrow';
    document.getElementById("mymap").childNodes[0].style.cursor = "";
    document.getElementById('QueryMapText').className='VEMapButtonNonSelected';
    document.getElementById('queryToolImg').className='QueryToolArrow';
    document.getElementById("mymap").childNodes[0].style.cursor = "";
    map.DetachEvent("onmousedown", queryMap);
    map.DetachEvent("onmousedown", zoomInStart);
    map.DetachEvent("onmousemove", zoomInBox);
    map.DetachEvent("onmouseup", zoomInEnd);
}

function queryMap (mapEvent)
{


    var queryPixel = new VEPixel(mapEvent.mapX, mapEvent.mapY);
    var queryLL = map.PixelToLatLong(queryPixel);



    var queryclickShape = new VEShape(VEShapeType.Pushpin, queryLL);
    queryveLLShape = new Array();
    queryveLLShape.push(queryclickShape); 
    
    map.DeleteAllShapes();
    map.AddShape(queryveLLShape);
    
    //Reproject the point
    var geoService = new ESRI.ArcGIS.VE.Geometry(geometryUrl); 
    //2276 is NAD_1983_StatePlane_Texas_North_Central_FIPS_4202_Feet 
    geoService.ProjectFromVEShapes(queryveLLShape, "2276", processQueryStatePlane); 


    bufferParams = new ESRI.ArcGIS.VE.BufferParameters(); 
    bufferParams.Geometries = queryveLLShape;
    bufferParams.Distances = [.5];
    bufferParams.Unit = ESRI.ArcGIS.VE.SRUnitTypes.NauticalMile; 
    geoService.Buffer(bufferParams, addBuffer);

    
}

var returnGeom;
var queryveLLShape;
var bufferShape;
function processQueryStatePlane(data)
{
    var err = data.Error;
    if (err!=null)
    {
        alert(err.message);
    }
    else 
    {
        returnGeom = data.geometries[0];
        $rest('REST.aspx?action=ReturnCensusHTML1&XCoord=' + returnGeom.x + '&YCoord=' + returnGeom.y + '&Radius=.5',queryResults);
    }
    
}
function addBuffer(data)
{
    var err = data.Error;
    if (err!=null)
    {
        alert(err.message);
    }
    else 
    {
        var rs = data.Shapes;
        var color = new VEColor(255,0,0,.15);
        var lineColor = new VEColor(0,0,0,.5); 
        if(rs && rs.length>0) {
            data.SetShapeStyle(lineColor, 2, color, false);
            bufferShape = data.ToVEShapeLayer();
            map.AddShapeLayer(bufferShape);
        } else
            alert("No buffer was returned. Unable to continue with query.");
    }
}

function queryResults(results)
{
    queryveLLShape[0].SetDescription(results);
    ExecuteParcelSearch();
}

var spatialQueryTask = null;
var spatialQueryParams = null;
var parcelDisplayData = "";

// function to send query request
function ExecuteParcelSearch() {
    // set appropriate parameter values
    spatialQueryParams = new ESRI.ArcGIS.VE.Query();
    // set parameter geometry to polyline
    spatialQueryParams.Geometry = queryveLLShape[0];
    //spatialQueryParams.SpatialRelationship = "esriSpatialRelCrosses";
    spatialQueryParams.OutFields = parcelSearchFields;           
    // create new query task
    spatialQueryTask = new ESRI.ArcGIS.VE.QueryTask();
    spatialQueryTask.Url = parcelUrl;
    // execute query request, passing parameters and response function
    spatialQueryTask.Execute(spatialQueryParams, addShapes); 
}


        // function to process query response
        function addShapes(data) {
            //var div = $get("job");
            //div.style.cursor = "default";
            // check for error. . . if none, add returned shapes to map
            var err = data.Error;
            if (err!=null)
            {
                //div.innerHTML = err.message;
            }
            else 
            {
                var rs = data.Features;
                var color = new VEColor(0,0,255,.15);
                var lineColor = new VEColor(0,0,0,.5); 
                if(rs && rs.length>0) {
                    data.SetShapeStyle(lineColor, 2, color, false);
                    parcelShape = data.ToVEShapeLayer();
                    if(data.Features.length>0)
                    {
                        parcelDisplayData = "<table class='ReportTable' cellpadding='0' cellspacing='0'><tr><td class='ReportTitle' colspan='2' ><b>Parcel Information</b></td></tr>";
                        var resultFeature = data.Features[0];
                        for(p in resultFeature.Attributes) {
                            for (var i=0;i <parcelFieldsJson.Fields.length;i++)
                            {
                                if (parcelFieldsJson.Fields[i].Name==p)
                                {
                                    var value = resultFeature.Attributes[p];
                                    if (parcelFieldsJson.Fields[i].Type!=null)
                                    {
                                        if(parcelFieldsJson.Fields[i].Type=="Money")
                                        {
                                            value = new Number(value);
                                            value = "$" + value.formatMoney(0);
                                        }
                                    }
                                    parcelDisplayData = parcelDisplayData + "<tr><td class='ReportColLeft'>" + parcelFieldsJson.Fields[i].Alias + ":</td><td class='ReportColRight'>" + value + "</td></tr>";
                                    if (parcelFieldsJson.Fields[i].Name=="ACCT_")
                                    var accountresult =  resultFeature.Attributes[p];
                                    break;
                                }
                            }
                        
                        }
                        parcelDisplayData = parcelDisplayData +  "<tr><td></td><td class='ReportColRight'><a href=http://www.dallascad.org/AcctDetailRes.aspx?ID=" + accountresult + " target=blank >more...</a></td></tr></table>";
                        var resultShape = parcelShape.GetShapeByIndex(0);
                        parcelDisplayData = parcelDisplayData + "</table>";
                        var resultShape = parcelShape.GetShapeByIndex(0);
                        
                        if(resultShape!=null)
                        {
                            queryveLLShape[0].SetDescription(parcelDisplayData+queryveLLShape[0].GetDescription());
                        }
                    }
                    parcelShape.SetTitle("ParcelResult");
                     parcelShape.SetDescription('<div style="width: 200px; background-color: black; color: blue"></div>');

                    map.AddShapeLayer(parcelShape);
                }
            }
            map.ShowInfoBox(queryveLLShape[0]);

        } 



function ChangeMap(action, distance)
{
    map.HideInfoBox();
    map.DeleteShapeLayer(bufferShape);
    var geoService = new ESRI.ArcGIS.VE.Geometry(geometryUrl); 


    bufferParams = new ESRI.ArcGIS.VE.BufferParameters(); 
    bufferParams.Geometries = queryveLLShape;
    bufferParams.Distances = distance;
    bufferParams.Unit = ESRI.ArcGIS.VE.SRUnitTypes.NauticalMile; 
    geoService.Buffer(bufferParams, addBuffer);

    $rest('REST.aspx?action=ReturnCensusHTML1&XCoord=' + returnGeom.x + '&YCoord=' + returnGeom.y + '&Radius=' + distance,queryResults);
}

function ExecuteTask() {
//alert(document.getElementById('DropDownList1').SelectedItem.Text);
   var qTask = new ESRI.ArcGIS.VE.QueryTask();
   qTask.Url = "http://gis.dfwmaps.com/ArcGIS/rest/services/Dallas/DallasCrime_VE/MapServer/1";
    var qParams = new ESRI.ArcGIS.VE.Query();
   
//alert (document.getElementById('ctl00_MapAppHolder_DropDownList1').options[document.getElementById('ctl00_MapAppHolder_DropDownList1').selectedIndex].value);
var selectedbeat = document.getElementById('ctl00_MapAppHolder_DropDownList1').options[document.getElementById('ctl00_MapAppHolder_DropDownList1').selectedIndex].value


   qParams.Where = "BEAT = " + selectedbeat +"";
   //alert("Beat:" + selectedbeat);
    qParams.OutFields = ["BEAT"];
   qTask.Execute(qParams, addShapes);
    
 }
 
 function ExecuteTask_HOA(){
 var qTask = new ESRI.ArcGIS.VE.QueryTask();
   qTask.Url = "http://gis.dfwmaps.com/ArcGIS/rest/services/Dallas/DallasCrime_VE/MapServer/3";
    var qParams = new ESRI.ArcGIS.VE.Query();
   
//alert (document.getElementById('ctl00_MapAppHolder_DropDownList1').options[document.getElementById('ctl00_MapAppHolder_DropDownList1').selectedIndex].value);
var selectedHOA = document.getElementById('ctl00_MapAppHolder_DropDownList3').options[document.getElementById('ctl00_MapAppHolder_DropDownList3').selectedIndex].value

var sqlstring = "ASSO_NAME = '" + selectedHOA + "'";
   qParams.Where = sqlstring;
   //alert("ASSO_NAME = " + selectedHOA + "");
    qParams.OutFields = ["ASSO_NAME"];
   qTask.Execute(qParams, addShapes);
 }
  
function ExecuteTask_NHA(){
 var qTask = new ESRI.ArcGIS.VE.QueryTask();
   qTask.Url = "http://gis.dfwmaps.com/ArcGIS/rest/services/Dallas/DallasCrime_VE/MapServer/4";
    var qParams = new ESRI.ArcGIS.VE.Query();
   
//alert (document.getElementById('ctl00_MapAppHolder_DropDownList1').options[document.getElementById('ctl00_MapAppHolder_DropDownList1').selectedIndex].value);
var selectedNHA = document.getElementById('ctl00_MapAppHolder_DropDownList4').options[document.getElementById('ctl00_MapAppHolder_DropDownList4').selectedIndex].value

var sqlstring = "ASSO_NAME = '" + selectedNHA + "'";
   qParams.Where = sqlstring;
   //alert("ASSO_NAME = " + selectedHOA + "");
    qParams.OutFields = ["ASSO_NAME"];
   qTask.Execute(qParams, addShapes);
 } 
  
function ExecuteTask_areas() {
//alert(document.getElementById('DropDownList1').SelectedItem.Text);
   var qTask = new ESRI.ArcGIS.VE.QueryTask();
   qTask.Url = "http://gis.dfwmaps.com/ArcGIS/rest/services/Dallas/DallasCrime_VE/MapServer/2";
    var qParams = new ESRI.ArcGIS.VE.Query();
   
//alert (document.getElementById('ctl00_MapAppHolder_DropDownList1').options[document.getElementById('ctl00_MapAppHolder_DropDownList1').selectedIndex].value);
var selectedra = document.getElementById('ctl00_MapAppHolder_DropDownList2').options[document.getElementById('ctl00_MapAppHolder_DropDownList2').selectedIndex].value


   qParams.Where = "RA = " + selectedra +"";
    qParams.OutFields = ["RA"];
   qTask.Execute(qParams, addShapes);
 }
  
 function addShapes(featureSetResults) {
 

 if(shapeLayer != null)         
        {            
       map.DeleteShapeLayer(shapeLayer); 
        shapeLayer = null;          
        }
    if (featureSetResults.Error != null)
       alert("Error: " + featureSetResults.Error.message);
    else {
    
        shapeLayer = featureSetResults.ToVEShapeLayer();
      
       map.AddShapeLayer(shapeLayer);
       rect = shapeLayer.GetBoundingRectangle();
        map.SetMapView(rect);
       

       map.SetZoomLevel(15);
             //map.SetCenter(); 
        //map.SetZoomLevel(13);
        //map.SetCenterAndZoom(new VELatLong(lat, lon), 13);
         
         
    }
 }
 
 



function openPrint()
{
    myWindow = window.open("", "tinyWindow", 'width=800,height=800,resizable=yes,scrollbars=yes'); 
    myWindow.document.write("<html>"); 
    myWindow.document.write("<body onload='document.getElementById(\"form1\").submit();'>"); 
    myWindow.document.write("<form id='form1' action='Print.aspx' method='POST'>"); 
    myWindow.document.write("<input type='hidden' name='mapX' value=''>"); 
    myWindow.document.write("<input type='hidden' name='mapY' value=''>"); 
    myWindow.document.write("<input type='hidden' name='mapLevel' value='" + map.GetZoomLevel() + "'>"); 
    myWindow.document.write("</form>"); 
    myWindow.document.write("</body>"); 
    myWindow.document.write("</html>"); 
    myWindow.document.close();
}

function openHelp()
{
    myWindow = window.open("http://www.dfwmaps.com", "tinyWindow", 'width=800,height=800,resizable=yes,scrollbars=yes'); 
}


function showLink()
{
    alert(map.GetZoomLevel());
    alert(map.GetCenter().Latitude);
    alert(map.GetCenter().Longitude);
    displayParcels = map.GetTileLayerByID("Parcels").IsVisible;
   displayDynamicMap = map.GetTileLayerByID("Land Base").IsVisible;
    displayDynamicMap = map.GetTileLayerByID("Crime").IsVisible;
}


Number.prototype.formatMoney = function(c, d, t){
    var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "",
    i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t)
    + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};


function browserSize() {
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    bWidth = window.innerWidth;
    bHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    bWidth = document.documentElement.clientWidth;
    bHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    bWidth = document.body.clientWidth;
    bHeight = document.body.clientHeight;
  }
}    

function SelectAddress() {
    //document.getElementById('querytool').className = 'QueryToolWrapper';
    toggleDiv('FindAddress');
}

function loadTOC() {
    //document.getElementById('querytool').className = 'QueryToolWrapper';
    toggleDiv('simpleTOC1');
}
function SelectDateRange() {
    //document.getElementById('querytool').className = 'QueryToolWrapper';
    toggleDiv('selectCrimeDate');
}
function toggleDiv(obj) {
    //expand or collapse the input div.  input is string containing ID of div
    var el = document.getElementById(obj);
    if (el.style.display != "none") {
        el.style.display = 'none';
    }
    else {
        el.style.display = '';
    }
}
