﻿var map = null;
var hidemap = null;
var index = 0;
var results = null;
var maxMapWidth = 800;
var maxMapHeight = 500;
var geocodepoint = null;


var bWidth = 0;
var bHeight = 0;
var slGeoRSS = new VEShapeLayer();
var GeoRSSAddToServiceId = 'Land Base';
var GeoRSSLayerId = -1; 

var agisve_services = null; 
var agis_services = new Array();
var identifyTolerance = 10; // in pixels 
        var identifyTask = null; 
        var identifyParameters = null;

        

        dojo.require("dijit.Toolbar");
        dojo.require("dijit.form.Button");
        dojo.require("dijit.layout.BorderContainer");
        dojo.require("dojo.parser");

        dojo.require("esri.map");

        dojo.addOnLoad(init);

function mapStartUp()
{

    browserSize();
    var mapwidth = bWidth-226;
    var mapheight = bHeight-202;
    if (mapwidth>maxMapWidth)
    {
        document.getElementById('mapWrapper').style.width=mapwidth+'px';
        document.getElementById('toolbar').style.width=(mapwidth+4)+'px';
        document.getElementById('tools').style.left=(mapwidth+28)+'px';
    }
    if (mapheight>maxMapHeight)
    {
        document.getElementById('mapWrapper').style.height=mapheight+'px';
        document.getElementById('simpleTOC1').style.height=(mapheight-158)+'px';
    }
    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);
    
    window.onresize = AdjustWebPage;
    
    ////Sonia Monga - 04/20/09 - Identify task
//     var parameters = {"LayerOption":"all", "LayerIds": [4,5], "Tolerance": identifyTolerance};
//       identifyParameters = new ESRI.ArcGIS.VE.IdentifyParameters(parameters);
//          identifyTask = new ESRI.ArcGIS.VE.IdentifyTask();
//          identifyTask.Url = dynamicUrl;
//          map.AttachEvent("onclick",getPoint);

    
}

function AdjustWebPage()
{
    browserSize();
    var mapwidth = bWidth-226;
    var mapheight = bHeight-160;
    if (mapheight>maxMapHeight)
    {
        document.getElementById('mapWrapper').style.height=mapheight+'px';
    }
    else
    {
        mapheight = maxMapHeight;
    }
    if (mapwidth>maxMapWidth)
    {
        document.getElementById('mapWrapper').style.width=mapwidth+'px';
    }
    else
    {
        mapwidth = maxMapWidth;
    }
    document.getElementById('toolbar').style.width=(mapwidth+4)+'px';
    document.getElementById('tools').style.left=(mapwidth+28)+'px';
    document.getElementById('simpleTOC1').style.height=(mapheight-158)+'px';
    map.Resize(mapwidth,mapheight);
}

function init()
{
    AddMap();
}
//document.getElementById('address').value,

//Initialization
function searchaddress()
{
//alert(document.getElementById('address').value);
            var addressstring = document.getElementById('address').value;
            //alert(addressstring);
            var Address = new String(addressstring);
            if (Address.length > 0) findAddress(addressstring);
  }          

function findAddress(theaddress)
        {
        
        var StringSearch = new String(theaddress)
        //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 ClearMap()
         {
            map.Clear();
         }
       
function GetCoordinates(layer, resultsArray, places, hasMore, veErrorMessage)
        {
        ClearMap()
        //Delete any existing geocodepoint
        if(geocodepoint != null)         
        {            
        map.DeleteShape(geocodepoint);            
        geocodepoint = null; 
          
        }
        
        if(places != null)  
        {
        //Places Were found
        findPlaceResults = places[0].LatLong;
        var geocodepoint = new VEShape(VEShapeType.Pushpin, findPlaceResults);
        geocodepoint.SetTitle(places[0].Name);
        geocodepoint.SetDescription(findPlaceResults.toString() + '<br>');
       //document.getElementById('address').innerHTML = places[0].Name;
        map.AddShape(geocodepoint);
       map.SetZoomLevel(17);
        }
        else
        {
        //No places were found
        alert("Address Not Found");
       //document.getElementById('address').innerHTML = ' ';
        }

        //End of Geocode Function
        } 

 


function AddMap() {




//    var agisvecontours_services = new ESRI.ArcGIS.VE.ArcGISLayerFactory();
//    agisvecontours_services.CreateLayer(contoursMapURL, "Contours", GetMap);   

//    var contourMapServiceLayer = new esri.layers.ArcGISTiledMapServiceLayer(contoursMapURL, {id:'Contours'});
//    agis_services[0] = contourMapServiceLayer;



    var agisve_services = new ESRI.ArcGIS.VE.ArcGISLayerFactory();
    agisve_services.CreateLayer(tileUrl, "Parcels", GetMap);   
      


    var tiledMapServiceLayer = new esri.layers.ArcGISTiledMapServiceLayer(tileUrl, {id:'Parcels'});
    //hidemap.addLayer(tiledMapServiceLayer);
    agis_services[0] = tiledMapServiceLayer;
    var dynamicMapServiceLayer = new esri.layers.ArcGISDynamicMapServiceLayer(dynamicUrl, {id:'Land Base'});
    //hidemap.addLayer(dynamicMapServiceLayer);
    
    agis_services[1] = dynamicMapServiceLayer;
    dojo.connect(dynamicMapServiceLayer,'onLoad',this,'loadLegend');
    
    //hidemap.addLayer(tiledMapServiceLayer);
 
    if(dynamicMapServiceLayer.layerInfos.length>0)
    {
        loadLegend();
    }
    
    //Enable Printing
    var printOpt = new VEPrintOptions(true);
     map.SetPrintOptions(printOpt);

}




function GetMap(tileSourceSpec, resourceInfo) {
    tileSourceSpec.Opacity=0.35;
    map.AddTileLayer(tileSourceSpec,showParcels);
   var url = "http://dallas.dfwmaps.com/handler.ashx?";
//            //url += "Lat=" + Lat;
//            //url += "&Lon=" + Lon;

            var veLayerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS, url, slGeoRSS);
           
           map.ImportShapeLayerData(veLayerSpec, onFeedLoad, false);
         slGeoRSS.Hide();
   
    
    
    
}

function onFeedLoad(feed)
         {
        
     var numShapes = slGeoRSS.GetShapeCount();
     for(var i=0; i < numShapes; ++i)
    {
        var s = slGeoRSS.GetShapeByIndex(i);
       s.SetCustomIcon("http://Dallas.dfwmaps.com/images/library.gif");
 	//s.SetCustomIcon("http://www.nctcog.org/weather/images/PTCLDY.GIF");

    }
}

//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);
    

    
}

function selectQueryTool()
{
    if (document.getElementById('QueryMapText').className=='VEMapButtonSelected')
    {
        document.getElementById('QueryMapText').className='VEMapButtonNonSelected';
        document.getElementById('queryToolImg').className='QueryToolArrow';
        document.getElementById("mymap").childNodes[0].style.cursor = "";
        map.DetachEvent("onmousedown", queryMap);
        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 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.");
    }
}
var censusDisplayData;
function queryResults(censusResults) {
    
    //draybuck: strip title out of census service HTML result so we can add it with some onclick toggle functionality
    censusResults = censusResults.replace('2000 Census Information', '')
    censusResults = "<a onclick='toggleDiv(\"censusresults\")';> <b>2000 Census Information</a></b><div id='censusresults' style='display:none'>" + censusResults + "</div><br>"
    //queryveLLShape[0].SetDescription(censusResults);

    censusDisplayData = censusResults;
    
    ExecuteQueries(); //code for querying various layers has been moved to query.js

}



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 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;
}


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 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 = '';
    }
}
//function getPoint(e) {



//            var clickPnt = null;
//            if (e.latLong) {
//                clickPnt = e.latLong;
//            } else {
//                var clickPixel = new VEPixel(e.mapX,e.mapY);
//                clickPnt = map.PixelToLatLong(clickPixel);
//            }
//            var pushpoint = new VEShape(VEShapeType.Pushpin, clickPnt);
//            //document.getElementById('myMap').style.cursor = "crosshair";
//            map.DeleteAllShapes();
//            identifyParameters.Geometry = pushpoint;
//            var mapDiv =  $get("mymap");
//            identifyParameters.Width = mapDiv.clientWidth;
//            identifyParameters.height = mapDiv.clientHeight;
//            identifyParameters.MapExtent = map.GetMapView();
//            identifyTask.Execute(identifyParameters, addShapespoints); 
//        }

//        function addShapespoints(identResults) {
//            var err = identResults.Error;
//            if (err!=null) 
//                alert(err.message);
//            else {
//                var shape = identResults.InputGeometry;
//                if (shape.GetDescription().length==0)
//                    shape.SetDescription("Unable to identify any map features at the click location.");
//                shape.Show();
//                map.AddShape(shape);
//            }
//         }       

