﻿var map = null;
var hidemap = null;
var index = 0;
var results = null;
var maxMapWidth = 520;  //draybuck:  make maxMapWidth and maxMapHeight values smaller to allow for smaller map resize threshold
var maxMapHeight = 400;
var geocodepoint = null;
var toolsoffset = 230; //adjust # to move query map, print, help and other buttons left or right

var bWidth = 0;
var bHeight = 0;

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("esri.map");

        dojo.addOnLoad(init);

function mapStartUp()
{
    // draybuck: modified this function to remove redundant map resize code that is commented out below.  added AdjustWebPage() function call
    // below as replacement.
    

    browserSize();
    var mapwidth = bWidth-240;
    var mapheight = bHeight-240;
    if (mapwidth>maxMapWidth)
    {
        document.getElementById('mapWrapper').style.width=mapwidth+'px';
        document.getElementById('toolbar').style.width=(mapwidth+4)+'px';
        document.getElementById('tools').style.left = (bWidth - toolsoffset) + 'px';
        //document.getElementById('footer').style.width = (bWidth - 23) + 'px';
    }
    if (mapheight>maxMapHeight)
    {
        document.getElementById('mapWrapper').style.height=mapheight+'px';
        document.getElementById('simpleTOC1').style.height = (mapheight - 165) + 'px';
        //document.getElementById('footer').style.width = (bWidth - 23) + 'px';
    }
    
   
    var startLatitude = 32.934232;
    var startLongitude = -97.229272;
    var startMapLevel = 12;
    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);

   // AdjustWebPage(); //draybuck:  add this in place of original browsersize() call and div resizings
    
    window.onresize = AdjustWebPage;
    
}

function AdjustWebPage()
{
    browserSize();
    var mapwidth = bWidth-240;
    var mapheight = bHeight-240;
    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 - toolsoffset) + 'px';  
    }
    else
    {
        mapwidth = maxMapWidth;
    }
   document.getElementById('toolbar').style.width = (mapwidth + 4) + 'px';
   document.getElementById('simpleTOC1').style.height = (mapheight - 165) + 'px';
  
   
    
    map.Resize();
}

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 Keller, TX not supplied, add it
        theaddress = StringSearch.replace(/keller/gi,'');
        theaddress = theaddress + ' , Keller, 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(document.getElementById('addressLabel').value);
        geocodepoint.SetDescription(places[0].Name + '<br>' + 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[1] = tiledMapServiceLayer;
    var dynamicMapServiceLayer = new esri.layers.ArcGISDynamicMapServiceLayer(dynamicUrl, {id:'Land Base'});
    //hidemap.addLayer(dynamicMapServiceLayer);
    
    agis_services[2] = dynamicMapServiceLayer;
    dojo.connect(dynamicMapServiceLayer,'onLoad',this,'loadLegend');
    
    //hidemap.addLayer(tiledMapServiceLayer);
    
    if(dynamicMapServiceLayer.layerInfos.length>0)
    {
        loadLegend();
    }
    
    var printOpt = new VEPrintOptions(true);
            map.SetPrintOptions(printOpt);

}

function GetMap(tileSourceSpec, resourceInfo) {
    tileSourceSpec.Opacity=0.35;
    map.AddTileLayer(tileSourceSpec,showParcels);
}
function loadLegend()
{

    var simpleTOC = dijit.byId('simpleTOC1');
    simpleTOC.init(map);    
    addDynamicService(map,"Land Base",dynamicUrl,getTilePathLandBase, 1,showDynMap);
    
    
}

//draybuck: moved code to unselect buttons to their own functions to eliminate repetition

function selectQueryTool()
{
    if (document.getElementById('QueryMapText').className=='VEMapButtonSelected')
    {
        unselectQueryTool();
    } 
    else
    {
        document.getElementById('QueryMapText').className='VEMapButtonSelected';
        document.getElementById('queryToolImg').className='QueryToolArrowSelected';
        document.getElementById("mymap").childNodes[0].style.cursor = "crosshair";
        map.AttachEvent("onmousedown", queryMap);
    }

    //unselect other buttons
    //unselectMeasureTool();
    hidePrintSizeForm();
      
}

function unselectQueryTool() {
    document.getElementById('QueryMapText').className = 'VEMapButtonNonSelected';
    document.getElementById('queryToolImg').className = 'QueryToolArrow';
    document.getElementById("mymap").childNodes[0].style.cursor = "";
    map.DetachEvent("onmousedown", queryMap);
    map.Clear();
    
}

function selectMeasureTool() {
    if (document.getElementById('MeasureToolText').className == 'VEMapButtonSelected') 
    {
        unselectMeasureTool();
        document.getElementById("mymap").childNodes[0].style.cursor = '';
    }
    else {
        document.getElementById('MeasureToolText').className = 'VEMapButtonSelected';
        document.getElementById('measureToolImg').className = 'QueryToolArrowSelected';
        startMeasureTool();
        document.getElementById("mymap").childNodes[0].style.cursor = "crosshair";
    }
    
    //unselect/deactivate query map button
    unselectQueryTool();
    hidePrintSizeForm();
}

function unselectMeasureTool() {
        document.getElementById('MeasureToolText').className = 'VEMapButtonNonSelected';
        document.getElementById('measureToolImg').className = 'QueryToolArrow';
        try {stopMeasureTool();}
        catch (err) {}
        map.Clear();
}


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(pageSize) {

    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?size=" + pageSize + "' method='POST'>");  //modified by draybuck
    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("help.htm", "tinyWindow", 'width=800,height=725,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;
  }
}

//added by draybuck for print size selection functionality
function showPrintSizeForm() {
    if (document.getElementById('printSizeForm').style.display == '') {
        hidePrintSizeForm();
    }
    else {

        document.getElementById('printSizeForm').style.display = '';
        document.getElementById('printSizeForm').style.left = bWidth - 180 + 'px';  //draybuck: currently you must adjust this offset manually to move the print Size form

        //turn off measure button
        try {
            unselectMeasureTool();
        }
        catch (err) { }
    }
}

function hidePrintSizeForm() {
    document.getElementById('printSizeForm').style.display = 'none';
}

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 = '';
    }
}
