﻿
$(document).ready(function(){
    dojo.require("esri.map");
    dojo.require("esri.tasks.locator");

    // FIX that takes into account the position in the document
    //(vs. in the browser window as before).
    dojo.global.esri.Map.prototype.reposition = function() {
        //console.log("Enter Map.reposition in esriJsMap.js");
        
        //var pos = dojo.coords(this.container),
        var pos = dojo.coords(this.container, true),
                brdr = dojo._getBorderExtents(this.container);

        this.position.setX(pos.x + brdr.l);
        this.position.setY(pos.y + brdr.t);
        this.onReposition(this.position.x, this.position.y);
        
        //console.log("Exit Map.reposition in esriJsMap.js");
    }
});

com.timmons.srl.esriJsMap = function() {

    //Declare private properties here
    var _map = null;
    var _mapElementId;
    var _geocoder;    
    var _foregroundGraphic = null;
    var _backgroundGraphic = null;    
    var _markers = [];
    var _address;
    var _configurationSettings = null;
    var _dataManager = null;
    var _latOut = null;
    var _lngOut = null;
    var idtask = null;
    var currentLocation = null;

    var _latLngIn = function(res) {
            _address.latitude = res[0];
            _address.longitude = res[1];
    };
        
    // Private Methods here
    var _initialize = function(mapElementId, configurationSettings, dataManager) {  
        //console.log('Enter com.timmons.srl.esriJsMap._initialize() in esrJsMap.js');
       
        
        _mapElementId = mapElementId;
        
        _configurationSettings = configurationSettings;
        
        _dataManager = dataManager;
        
        _dataManager.GetMapAndTileFields(this._setMapPageAndTileValues, _setMapPageAndTileValues);
        
        idtask = new esri.tasks.IdentifyTask(_configurationSettings.mapServices[1].url);
        
        try{
            _geocoder = new esri.tasks.Locator(_configurationSettings.locatorServices[0].url);
        }catch(ex){
            console.warn(ex);
        }

        //return _createMap(mapElementId);        
        
        //console.log('Exit com.timmons.srl.esriJsMap._initialize() in esrJsMap.js');
        $('#AddressCandidatesClose').click(function(){
            $('#AddressCandidates').hide('slow');
        });
        
    };

    var _setMapPageAndTileValues = function(results){
        /*
          results.KMAPFIELDNAME: "COUN_NAME"
          results.KMAPTHEMENAME: "Council_Districts"
          results.TILENOFIELDNAME: "DST_NUM"
          results.TILENOTHEMENAME: "Council_Districts"
        */
        
        if(results.KMAPFIELDNAME){
            _configurationSettings.MapPageField = results.KMAPFIELDNAME;
        }
        
        if(results.TILENOFIELDNAME){
            _configurationSettings.TileField = results.TILENOFIELDNAME;
        }
        
    };

    var _createMap = function(obj, callback) {
        //console.log('Enter com.timmons.srl.esriJsMap._createMap() in esrJsMap.js');
        
        
        if (!document.getElementById(_mapElementId)) {
            throw "A valid HTML element on the page is required for creating a map.";
        } else {

            if (_configurationSettings) {

                if (!_configurationSettings.width && !_configurationSettings.height) {

                    dojo.style("map_canvas", "backgroundColor", "white");
                    
                    //extent: new esri.geometry.Extent({xmin:-20098296,ymin:-2804413,xmax:5920428,ymax:15813776,spatialReference:{wkid:54032}})
                     esriConfig.defaults.map.slider = { right:"10px", top:"10px", width:"40px", height:"200px" };
                    _map = new esri.Map(
                        _mapElementId,
                        {
                            extent : new esri.geometry.Extent(_configurationSettings.extent)
                        }                    
                    );

                    //dojo.connect(_map, "onClick", function(evt) {
                        //_map.graphics.clear();
                        
                      //_addMainMarker(esri.geometry.webMercatorToGeographic(evt.mapPoint));
                        
                        //_geocoder.locationToAddress(esri.geometry.webMercatorToGeographic(evt.mapPoint), 100);
                        
                    //});                    
                    
                    if(_map.loaded == false){
                        _map.reposition();
                    }else{
                        var mapRepositionOnLoadHandle = dojo.connect(
                            _map,
                            "onLoad",
                            function(){
                                dojo.disconnect(mapRepositionOnLoadHandle);
                                _map.reposition();
                            }
                        );
                    }
                    
                    if(_map.Loaded == true){
                        if (callback) {
                            callback.call(obj);
                        }
                    }else{
                        var mapOnLoadHandle = dojo.connect(
                            _map,
                            "onLoad",
                            function(){
                                dojo.disconnect(mapOnLoadHandle);
                                if (callback) {
                                    callback.call(obj);
                                }                                    
                            }
                        );
                    }
                    
                    var imageParameters = new esri.layers.ImageParameters();
                    imageParameters.format = "png24";
                    esriConfig.defaults.map.slider = { left: "20px", top: "80px", width: null, height: "100px" };
                    
                    dojo.forEach(
                        _configurationSettings.mapServices,
                        function(item){                            
                            if(item.layerType == com.timmons.srl.configManager.layerType.dynamicMapServiceLayer){
                                var dynamicMapServiceLayer = new esri.layers.ArcGISDynamicMapServiceLayer(
                                    item.url,
                                    { "imageParameters": imageParameters , "opacity": item.opacity}
                                );
                                _map.addLayer(dynamicMapServiceLayer);
                            }else if(item.layerType == com.timmons.srl.configManager.layerType.tiledMapServiceLayer){
                                var tiledMapServiceLayer = new esri.layers.ArcGISDynamicMapServiceLayer(
                                    item.url
                                );
                                _map.addLayer(tiledMapServiceLayer);
                            }        
                        }
                    );

                } else {
                
                    dojo.style("map_canvas", "backgroundColor", "white");
                    esriConfig.defaults.map.slider = { right:"10px", top:"10px", width:"40px", height:"200px" };
                    _map = new esri.Map(
                        _mapElementId,
                        {
                            extent : new esri.geometry.Extent(_configurationSettings.extent)
                        }                    
                    );
                                        
                    if(_map.loaded == false){
                        _map.reposition();
                    }else{
                    
                        var mapRepositionOnLoadHandle = dojo.connect(
                            _map,
                            "onLoad",
                            function(){
                                dojo.disconnect(mapRepositionOnLoadHandle);
                                _map.reposition();
                            }
                        );
                    }
                    
                    var imageParameters = new esri.layers.ImageParameters();                    
                    imageParameters.format = "png24";
                    esriConfig.defaults.map.slider = { left: "20px", top: "80px", width: null, height: "100px" };
                    
                    dojo.forEach(
                        _configurationSettings.mapServices,
                        function(item){                            
                            if(item.layerType == com.timmons.srl.configManager.layerType.dynamicMapServiceLayer){
                                var dynamicMapServiceLayer = new esri.layers.ArcGISDynamicMapServiceLayer(
                                    item.url, 
                                    { "imageParameters": imageParameters }
                                );
                                _map.addLayer(dynamicMapServiceLayer);
                            }else if(item.layerType == com.timmons.srl.configManager.layerType.tiledMapServiceLayer){
                                var tiledMapServiceLayer = new esri.layers.ArcGISDynamicMapServiceLayer(
                                    item.url
                                );
                                _map.addLayer(tiledMapServiceLayer);
                            }        
                        }
                    );                    
                }
            }
        }
        return true;
    };

    /**
    Hide the page loading image after a delay of time to allow the user to see it.
    If provided, call the callback function passed in along with the parameters for the callback.
    */
    var _hidePageLoading = function(obj, callback, parameters) {

        $('#srlPageLoadingImage').fadeTo(1000, 1, function() {

            //$('#srlPageLoadingModal').dialog('close');
            $('#srlPageLoadingModal').hide();
        
            if (callback) callback.call(obj, parameters);
        });
    };
    
    var addressCandidates = {};
    var currentCityName = null;
    function candidatesNeeded(addresses, obj, callback, isIntersectionAddress){
        if(addresses){
            if(addresses.length === 1){
                return false;
            }
            
            addressCandidates = {};

            if(isIntersectionAddress){
                return processIntersectionAddress(addresses, obj, callback);
            }else{
                if(addresses.length > 1){
                    if(addresses[0].score === addresses[1].score){
                        return processStreetAddressCandidates(addresses, obj, callback);
                    }else{
                        return processStreetAddress(addresses, obj, callback);
                    }
                }else{
                    return processStreetAddress(addresses, obj, callback);
                }
            }
        }
        return false;
    }
    
    function processStreetAddressCandidates(addresses, obj, callback){
        //First, lets get all the candidates w/ the matching high score
        var currentScore = -1;
        var candidateAddresses = [];
        currentScore = -1;
        candidateAddresses = [];
        
        for(var i = 0; i != addresses.length; i++){
            if(currentScore === -1){
                currentScore = addresses[i].score;
                candidateAddresses[candidateAddresses.length] = addresses[i];
            }else{
                if(addresses[i].score < currentScore){
                    break;
                }else{
                    candidateAddresses[candidateAddresses.length] = addresses[i];
                }
            }
        }
        
        var cities = [];
        var citiesString = '';
        var html = '';
        
        cities = [];
        citiesString = '';
        html = '';
        addressCandidates = [];
        
        for(x = 0; x!= candidateAddresses.length; x++)
        {
            citiesString = cities.toString();
            if(citiesString.search(candidateAddresses[x].attributes.LeftZone) === -1){
                cities[cities.length] = candidateAddresses[x].attributes.LeftZone;
                var currentCity = candidateAddresses[x].attributes.LeftZone;
                html += '<div>';
                    html += '<input class="addressCandidate" type="radio" id="addressCandidate_' + cities.length + '" value=' + 
                    cities.length + ' name=\'cityCandidate\' cityName="' + currentCity + '" />' + currentCity
                html += '</div>';
                
                addressCandidates[cities.length-1] = addresses[x];
            }
            
            citiesString = cities.toString();
            if(citiesString.search(candidateAddresses[x].attributes.RightZone) === -1){
                cities[cities.length] = candidateAddresses[x].attributes.RightZone;
                var currentCity = candidateAddresses[x].attributes.RightZone;
                html += '<div>';
                    html += '<input class="addressCandidate" type="radio" id="addressCandidate_' + cities.length + '" value=' + 
                    cities.length + ' name=\'cityCandidate\' cityName="' + currentCity + '" />' + currentCity
                html += '</div>';
                
                addressCandidates[cities.length-1] = addresses[x];
            }
        }
            
        if(cities.length > 1){
            $('input.addressCandidate').die();
            $('input.addressCandidate').live('click', function() {
                citySelected(this, obj, callback);
            });
            
            $('#AddressCandidateList').html(html);
            $('#AddressCandidates').show("slow")
            
            return true;
        }
        if(cities.length === 1){
            return false;
        }else{
            return true;
        }
    }
    
    function processStreetAddress(addresses, obj, callback){
        if(addresses[0].attributes){
            if(addresses[0].attributes.LeftZone && addresses[0].attributes.RightZone){
                if(addresses[0].attributes.LeftZone === addresses[0].attributes.RightZone){
                    currentCityName = addresses[0].attributes.LeftZone;
                    setCityValue();
                    return false;    
                }else{
                    var addressParts = addresses[0].address.split(' ');
                    var addressNbr = addressParts[0];
                    //currentCityName
                    if (addressNbr %2 === 0){
	                    //"Even" = LeftZone
	                    currentCityName = addresses[0].attributes.LeftZone;
                    }else{
	                    //"Odd" = RightZone
	                    currentCityName = addresses[0].attributes.RightZone;
                    }
                    setCityValue();
                    
                    return false;
                }
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    function processIntersectionAddress(addresses, obj, callback){
        var cities = [];
        var citiesString = '';
        var html = '';
        
        cities = [];
        citiesString = '';
        html = '';
        addressCandidates = [];
        
        for(x = 0; x!= addresses.length; x++)
        {
            citiesString = cities.toString();
            if(citiesString.search(addresses[x].attributes.LeftZone1) === -1){
                cities[cities.length] = addresses[x].attributes.LeftZone1;
                var currentCity = addresses[x].attributes.LeftZone1;
                html += '<div>';
                    html += '<input class="addressCandidate" type="radio" id="addressCandidate_' + cities.length + '" value=' + 
                    cities.length + ' name=\'cityCandidate\' cityName="' + currentCity + '" />' + currentCity
                html += '</div>';
                
                addressCandidates[cities.length-1] = addresses[x];
            }
            
            citiesString = cities.toString();
            if(citiesString.search(addresses[x].attributes.RightZone1) === -1){
                cities[cities.length] = addresses[x].attributes.RightZone1;
                var currentCity = addresses[x].attributes.RightZone1;
                html += '<div>';
                    html += '<input class="addressCandidate" type="radio" id="addressCandidate_' + cities.length + '" value=' + 
                    cities.length + ' name=\'cityCandidate\' cityName="' + currentCity + '" />' + currentCity
                html += '</div>';
                
                addressCandidates[cities.length-1] = addresses[x];
            }

            citiesString = cities.toString();
            if(citiesString.search(addresses[x].attributes.LeftZone2) === -1){
                cities[cities.length] = addresses[x].attributes.LeftZone2;
                var currentCity = addresses[x].attributes.LeftZone2;
                html += '<div>';
                    html += '<input class="addressCandidate" type="radio" id="addressCandidate_' + cities.length + '" value=' + 
                    cities.length + ' name=\'cityCandidate\' cityName="' + currentCity + '" />' + currentCity
                html += '</div>';
                
                addressCandidates[cities.length-1] = addresses[x];
            }
            
            citiesString = cities.toString();
            if(citiesString.search(addresses[x].attributes.RightZone2) === -1){
                cities[cities.length] = addresses[x].attributes.RightZone2;
                var currentCity = addresses[x].attributes.RightZone2;
                html += '<div>';
                    html += '<input class="addressCandidate" type="radio" id="addressCandidate_' + cities.length + '" value=' + 
                    cities.length + ' name=\'cityCandidate\' cityName="' + currentCity + '" />' + currentCity
                html += '</div>';
                
                addressCandidates[cities.length-1] = addresses[x];
            }
        }
            
        if(cities.length > 1){
            $('input.addressCandidate').die();
            $('input.addressCandidate').live("click", function() {
                citySelected(this, obj, callback);
            });            
            
            $('#AddressCandidateList').html(html);
            $('#AddressCandidates').show("slow")
            
            return true;
        }
        if(cities.length === 1){
            return false;
        }else{
            return true;
        }       
    }

    function citySelected(elem, obj, callback){
       // alert(addressCandidates[$(elem).val()-1].attributes.Match_addr + '\r\n' + $(elem).attr('cityName'));
       $('#AddressCandidates').hide("slow")
       currentCityName = $(elem).attr('cityName');
       processGeocodedAddress(addressCandidates[$(elem).val()-1], obj, callback, currentCityName);
    }
    
    
    // addAddressToMap() is called when the geocoder returns an
    // answer.  It adds a marker to the map with an open info window
    // showing the nicely formatted version of the address and the country code.
    var outFields = null;
    
    var _geocodeAddress = function(address, obj, callback, fromReverseGeocoder) {
        console.log('Enter com.timmons.srl.esriJsMap._geocodeAddress() in esrJsMap.js');
        currentCityName = null;
        $('input.addressCandidate').die();
        $('#AddressCandidateList').html('');
        $('#AddressCandidates').hide("slow");
        
        _clearMap();

        var isIntersectionAddress = false;

        //Make correct format...
        address = address.toUpperCase();
        if(address.indexOf(' AND ') > 0){
            address = address.replace(' AND ', ' & ');
        }
        
        if(address.indexOf(' & ') > 0){
            isIntersectionAddress = true;
        }else{
            isIntersectionAddress = false;
        }
        
        //Remove [, City] from address
        if(address.indexOf(',') > 0){
            var addressParts = address.split(',');
            var addressTemp = '';
            addressTemp = '';
            for(var i = 0; i != addressParts.length; i++){
                if(i < addressParts.length - 1){
                    addressTemp += addressParts[i];
                }
            }
            
            address = addressTemp;
        }
        
        var esriAddress = {
            //FindAddresses: address
            Street: address
        };

        try{
        outFields = new Array();
        
        if(address.indexOf(' & ') > 0){
            outFields[0] = "Side";
            outFields[1] = "X";
            outFields[2] = "Y";
            outFields[3] = "PreDir1";
            outFields[4] = "PreType1";
            outFields[5] = "StreetName1";
            outFields[6] = "Type1";
            outFields[7] = "LeftZone1";
            outFields[8] = "RightZone1";
            outFields[9] = "PreDir2";
            outFields[10] = "PreType2";
            outFields[11] = "StreetName2";
            outFields[12] = "Type2";
            outFields[13] = "LeftZone2";
            outFields[14] = "RightZone2";            
            outFields[15] = "Match_addr";
        }else{
            outFields[0] = "Side";
            outFields[1] = "X";
            outFields[2] = "Y";
            outFields[3] = "PreDir";
            outFields[4] = "PreType";
            outFields[5] = "StreetName";
            outFields[6] = "StreetType";
            outFields[7] = "SufDir";
            outFields[8] = "LeftZone";
            outFields[9] = "RightZone";
            outFields[10] = "Match_addr";
            
        }
                
            _geocoder.addressToLocations(
                esriAddress,
                outFields,
                function(addresses) {
                    console.log('Enter addressToLocations callback');

                    try{
                        if(addresses && addresses[0]){
                            if(candidatesNeeded(addresses, obj, callback, isIntersectionAddress)){
                                //Show Candidates Selector if applicable
                                _hidePageLoading($('#AddressCandidates').show("slow"));
                                return;
                            }else{
                                processGeocodedAddress(addresses[0], obj, callback, fromReverseGeocoder);
                            }
                        }else{
                            alert("Sorry, we were unable to locate that address.  Please enter another address and try again.");
                            callback();
                        }
                    }catch(ex){
                        console.warn(ex);
                    }
                    console.log('Exit addressToLocations callback');
                },
                function(error) {
                    console.log('Enter addressToLocations errback');

                    console.warn(error);
                    
                    try{
                        callback.call(obj, false);
                    }catch(ex){
                        console.warn(ex);
                    }

                    console.log('Exit addressToLocations errback');
                }
            );
            
        }catch(ex){
            console.warn(ex);
        }
        
        console.log('Exit com.timmons.srl.esriJsMap._geocodeAddress() in esrJsMap.js');
    };

    function processGeocodedAddress(address, obj, callback, fromReverseGeocoder){
       // _setAddressValues(address, obj, callback);

        runIdentify(address, obj, callback, address.location);

        //The callback for this function is used later...
        _addMainMarker(address, obj, callback);

        var pext = new esri.geometry.Extent({ "xmin": address.location.x, "ymin": address.location.y, "xmax": address.location.x, "ymax": address.location.y, "spatialReference": _map.spatialReference });
        pext.xmin = pext.xmin - 5;
        pext.xmax = pext.xmax + 5;
        pext.ymin = pext.ymin - 5;
        pext.ymax = pext.ymax + 5;
        _map.setExtent(pext.expand(100.0));
        
        if(currentCityName){
            setCityValue();
        }
    }

    var _setAddressValues = function(place, obj, callback) {
        
        //_address = _createAddressJson(place);
        callback.call(obj, true);
        
    };

    function setCityValue(){
        var addressIn = $('#AddressIn').val().split(',');
        var addressOut = addressIn[0] + ', ' + currentCityName;
        $('#AddressIn').val(addressOut.toUpperCase());
    }

    var _addMainMarker = function(point, obj, callback) {
        //console.log('Enter com.timmons.srl.esriJsMap._addMainMarker() in esrJsMap.js');
        
        var markerHTML = _setMainMarkerInfo(point);
        var infoTemplate = new esri.InfoTemplate('Your Request', markerHTML);
                
        if(_foregroundGraphic && _foregroundGraphic != null){
            _map.graphics.remove(_foregroundGraphic);
        }
        
        if(_backgroundGraphic && _backgroundGraphic != null){
            _map.graphics.remove(_backgroundGraphic);
        }

        _backgroundGraphic = null;
        _backgroundGraphic = new esri.Graphic(
            point.location,
            new esri.symbol.PictureMarkerSymbol("images/shadow50.png", 37, 34).setOffset(10, 16),
            null,
            null
        );
        _map.graphics.add(_backgroundGraphic);
        _foregroundGraphic = null;
        _foregroundGraphic = new esri.Graphic(
            point.location,
            new esri.symbol.PictureMarkerSymbol("images/marker.png", 20, 34).setOffset(0, 16),
            //getSimpleMarkerSymbol(),
            point.address,
            infoTemplate
        );

        _map.infoWindow.setTitle(_foregroundGraphic.getTitle()); // kludge
        _map.infoWindow.setContent(_foregroundGraphic.getContent()); // kludge
//        _map.infoWindow.show(
//            _map.toScreen(point.location), 
//            _map.getInfoWindowAnchor(_map.toScreen(point.location))
//        );

        try{
            if(_foregroundGraphic.getDojoShape() != null){
                dojo.style(dojoShape.getNode(), "cursor", "pointer");
            }
        }catch(ex){
            console.warn(ex);        
        }

        if(graphicsOnMouseDownHandle){
            graphicsOnMouseDownHandle = null;
        }
        
        var graphicsOnMouseDownHandle = dojo.connect(
            _map.graphics,
            "onMouseDown",
            function(e) {
                
                var mapOnMouseDragHandle = null;
                var mapOnMouseDragEndHandle = null;
                
                //capture the offset
                var offsetX =  e.mapPoint.x - _foregroundGraphic.geometry.x;
                var offsetY = e.mapPoint.y - _foregroundGraphic.geometry.y;
            
                _map.disablePan();
                
                try{
                    if(_foregroundGraphic.getDojoShape() != null){                    
                        dojo.style(_foregroundGraphic.getDojoShape().getNode(), "cursor", "move");
                    }
                }catch(ex){
                    console.warn(ex);
                }
                mapOnMouseDragHandle = dojo.connect(
                    _map,
                    "onMouseDrag",
                    function(e) {                        
                        _foregroundGraphic.setGeometry(
                            new esri.geometry.Point(
                                {x : (e.mapPoint.x - offsetX), y : (e.mapPoint.y - offsetY) }
                            )
                        );                    
                        _backgroundGraphic.setGeometry(
                            new esri.geometry.Point(
                                {x : (e.mapPoint.x - offsetX), y : (e.mapPoint.y - offsetY) }
                            )
                        );
                        _map.infoWindow.hide();                        
                    }
                );
                
                mapOnMouseDragEndHandle = dojo.connect(
                    _map,
                    "onMouseDragEnd",
                    function(e){                        
                        dojo.disconnect(mapOnMouseDragHandle);
                        dojo.disconnect(mapOnMouseDragEndHandle);                        
                        if (point.location.x !== _foregroundGraphic.geometry.x || point.location.y !== _foregroundGraphic.geometry.y){
                            _reverseGeocode(_foregroundGraphic, obj, callback);
                        }                    
                        try{
                            if(_foregroundGraphic.getDojoShape() != null){    
                                dojo.style(_foregroundGraphic.getDojoShape().getNode(), "cursor", "pointer");
                            }
                        }catch(ex){
                            console.warn(ex);
                        }                        
                        _map.enablePan();
                    }
                );
            }
        );
    };

    var _reverseGeocode = function(graphic, obj, callback) {
        //console.log('Enter com.timmons.srl.esriJsMap._reverseGeocode() in esrJsMap.js');
        try{
            currentCityName = null;
            
            _geocoder.locationToAddress(
                graphic.geometry, 
                100, 
                function(response) {
                    //console.log('Enter locationToAddress callback');
                    
                    try{
                      var address = {
                        street: response.address.Street,
                        city: response.address.Zone
                      };
                        response.location.x = graphic.geometry.x;
                        response.location.y = graphic.geometry.y;
                        
                        processGeocodedAddress(response, obj, callback); 
                        
                        //_setAddressValues(response);
                        
                        //_addMainMarkerEvents(place);

                        
                        //callback.call(obj, true);
                        
                    }catch(ex){
                        console.warn(ex);                    
                    }
                    //console.log('Exit locationToAddress callback');
                }, 
                function(error) {
                    //console.log('Enter locationToAddress errback');
                    
                    console.warn(error);
                    
                    try{
                        _map.enablePan();
                        callback.call(obj, false);                    
                    }catch(ex){
                        console.warn(ex);
                    }
                    
                    //console.log('Exit locationToAddress errback');
                }
            );        
        }catch(ex){
            console.warn(ex);
        }
        
        //console.log('Exit com.timmons.srl.esriJsMap._reverseGeocode() in esrJsMap.js');
    };

    var _addMarkers = function(markersJson) {
        //console.log('Enter com.timmons.srl.esriJsMap._addMarkers() in esrJsMap.js');
        
        //clear out the old markers, if any
        dojo.forEach(
            _markers,
            function(item){
                _map.graphics.remove(item);
            }
        );
        
        //(re)initialize the array;
        _markers = [];
        
        dojo.forEach(
            markersJson,
            function(item){            
                try{
                    var markerHTML = "";
                    //Status Line:  Status: OPEN
                    markerHTML += '<div class="MarkerStatusTD"><b>Status: </b>' + item.Status + '</div>';

                    //Code:         Code/Description: Alley Asphalt Repair - 2997A0000010 Alley Asphalt Repair
                    markerHTML += '<div class="MarkerTD"><b>Code/Description: </b>' +
                                        item.PROBLEMCODE + ' - ' + item.DESCRIPTION + '</div>';

                    //Date:         Date/Time Request Reported: 
                    //              7/30/2008 8:49:24 PM
                    markerHTML += '<div class="MarkerStatusTD"><b>Date/Time Request Reported:</b></div>';
                    markerHTML += '<div class="MarkerTD">' + item.DATETIMEINIT + '</div>';

                    if (item.WORKORDERID != "") {
                        //Date:         Workorder Assigned:
                        markerHTML += '<div class="MarkerTD"><b>******************</b></div>';
                        markerHTML += '<div class="MarkerTD"><b>Work Order Assigned</b></div>';
                    }

                    var symbol = new esri.symbol.PictureMarkerSymbol(
                        "images/ExistingRequest.png", 
                        30, 
                        30
                    );
                    
                    var infoTemplate = new esri.InfoTemplate();
                    infoTemplate.setTitle('Existing Request Details ');
                    infoTemplate.setContent(markerHTML);
                    
                    var graphic = new esri.Graphic(
                        new esri.geometry.Point(item.SRX, item.SRY), 
                        symbol, 
                        { address: item.address }, 
                        infoTemplate
                    );
                   
                    _markers.push(_map.graphics.add(graphic));                    
                
                }catch(ex){
                    console.warn(ex);
                }
            }
        );
        
        //float back to the top
        _map.graphics.remove(_foregroundGraphic);
        _map.graphics.remove(_backgroundGraphic);        
        _map.graphics.add(_backgroundGraphic);
        _map.graphics.add(_foregroundGraphic);        
        
        //console.log('Exit com.timmons.srl.esriJsMap._addMarkers() in esrJsMap.js');
    };

    var _hideMarkerHTML = function(pMarker, pMarkerHTML) {
        //console.log('Enter com.timmons.srl.esriJsMap._hideMarkerHTML() in esrJsMap.js');
    
        var gInfoWin = _map.getInfoWindow();
        pMarker.closeInfoWindow();
        
        //console.log('Exit com.timmons.srl.esriJsMap._hideMarkerHTML() in esrJsMap.js');
    };

    var _showMarkerHTML = function(pMarker, pMarkerHTML) {
        //console.log('Enter com.timmons.srl.esriJsMap._showMarkerHTML() in esrJsMap.js');
    
        var gInfoWin = _map.getInfoWindow();
        if (gInfoWin.isHidden() == true) {
            pMarker.openInfoWindowHtml(pMarkerHTML);
        }
        
        //console.log('Exit com.timmons.srl.esriJsMap._showMarkerHTML() in esrJsMap.js');        
    };

    var _getAddress = function() {

        return _address;
    };

    var mapNbr = '';
    var tile = '';
    function runIdentify(address, obj, callback, pointFromLocator){
        mapNbr = '';
        tile = '';
        var idparams = new esri.tasks.IdentifyParameters();
        var point = new esri.geometry.Point(pointFromLocator.x,pointFromLocator.y,_map.spatialReference);
        
        idparams.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_ALL;
        idparams.geometry = point;
        //idparams.tolerance = 1;
        idparams.tolerance = 0;
        idparams.mapExtent = _map.extent;
        idparams.spatialReference = new esri.SpatialReference({ wkid:102682 });
        idparams.width = _map.width;
        idparams.height = _map.height;
        idparams.layerIds = [0];
        
        //COUN_NAME: "Brandon Shelvin"
        //DST_NUM: "3"
        idtask.execute(idparams,
            function idcallback(idresults) {
                if(idresults[0]){ 
                    if(idresults[0].feature.attributes){
                    
                        mapNbr = idresults[0].feature.attributes[_configurationSettings.MapPageField];
                        tile = idresults[0].feature.attributes[_configurationSettings.TileField];
                    }
                     _createAddressJson(address, obj, callback, pointFromLocator);
                }
            }, 
            errorBack);
    }
    
    function errorBack(agsError){
      //  alert(agsError);
    }
    

    
    var _createAddressJson = function(place, obj, callback, pointFromLocator) {
        //console.log('Enter com.timmons.srl.esriJsMap._createAddressJson() in esrJsMap.js');
        
        var locality;
        var street = "";
        var city = "";
        var state = "";
        var zip = "";
        var latitude = 0;
        var longitude = 0;

        if (place.address){
            if(place.address.Street){
                street = place.address.Street;
                city = place.address.Zone;
            }else{
                street = place.address;
                var streetParts = street.split(',');
                if(streetParts.length === 2){
                    street = streetParts[0];
                }
            }
        }
        
//        if(place.Side =='R'){
//            city = place.attributes.RightZone;
//        }else{
//            city = place.attributes.LeftZone;
//        }
//        
//        if(place.attributes.Side =='R'){
//            city = place.attributes.RightZone;
//        }else{
//            city = place.attributes.LeftZone;
//        }
                
        if(currentCityName){
            if(currentCityName !== null){
                city = currentCityName;
            }
        }
        

        
        //street += ', ' + city;
        //place.address = place.address.replace(', ' + city,'');
        //place.address = street;
        
        //if (place.address){
            //street = place.address;
         //}
        
        if (place.location) {

            latitude = place.location.y;
            longitude = place.location.x;
            
            xyIn = latitude + ',' + longitude;
            //_dataManager.convertToLatLng(xyIn, this._latLngIn, _latLngIn);
        };

        var addressVal = {

            "street": street,
            "city": city,
            "state": state,
            "zip": zip,
            "latitude": latitude,
            "longitude": longitude,
            "address": street,
            "mapPage": mapNbr,
            "tile": tile
        }
        
        _address = addressVal;
        
        //console.log('Exit com.timmons.srl.esriJsMap._createAddressJson() in esrJsMap.js');
        //return address;
        
        _setAddressValues(place, obj, callback);
    };

    var _setMainMarkerInfo = function(point) {
        //console.log('Enter com.timmons.srl.esriJsMap._setMainMarkerInfo() in esrJsMap.js');
        
        var markerHTML = "";
        
        markerHTML += '<div><strong>Address:</strong></div>';

        if (_address) {

            if (_address.street) {

                markerHTML += '<div>' + _address.street + '</div>';
            }

            if (_address.city || _address.state || _address.zip) {

                markerHTML += '<div>';

                if (_address.city) markerHTML += _address.city;
                if (_address.state) markerHTML += ', ' + _address.state;
                if (_address.zip) markerHTML += ' ' + _address.zip;

                markerHTML += '</div>';
            }

            markerHTML += '<div class="srlInstructions">Drag the marker to adjust the location of the request</div>';

        } else {
            if(point){
                if(point.attributes){
                    if(point.attributes.Match_addr){
                        markerHTML += '<div>' + point.attributes.Match_addr + '</div>';
                        markerHTML += '<div class="srlInstructions">Drag the marker to adjust the location of the request</div>';                    
                    }else{
                        markerHTML += '<div>No Address found</div>';
                    }
                }else{
                    markerHTML += '<div>No Address found</div>';
                }
            }else{
                markerHTML += '<div>No Address found</div>';
            }
        }

        //console.log('Exit com.timmons.srl.esriJsMap._setMainMarkerInfo() in esrJsMap.js');
        return markerHTML;
    };

    var _clearMap = function() {

        _foregroundGraphic = null;
        _backgroundGraphic = null;        
        _markers = [];

        if (_map) {
            _map.graphics.clear();
            if (_map.infoWindow) _map.infoWindow.hide();
        }
    };

    var _refreshMap = function() {

        var extent = _map.extent;
        var center = extent.getCenter();

        var handle = dojo.connect(_map, "onResize", function() {

            dojo.disconnect(handle);
            _map.centerAt(center);
            _map.reposition();
        });

        _map.resize();
    };

    return {
        //Declare public properties here
        //Declare public methods here
        initialize: function(mapElementId, configurationSettings, dataManager) {
            
            return _initialize(mapElementId, configurationSettings, dataManager);
        },
        isMapCreated: function() {

            if (_map == null) return false;
            else return true;
        },
        createMap: function(obj, callback) {
            //console.log("Enter com.timmons.srl.esriJsMap.createMap() in esriJsMap.js");
            
            _createMap(obj, callback);            
            //console.log("Exit com.timmons.srl.esriJsMap.createMap() in esriJsMap.js");
        },
        refreshMap: function() {
            //console.log("Enter com.timmons.srl.esriJsMap.refreshMap() in esriJsMap.js");
            
            _refreshMap();
            //console.log("Exit com.timmons.srl.esriJsMap.refreshMap() in esriJsMap.js");
        },
        geocodeAddress: function(address, cityStateList, obj, callback) {
            //console.log("Enter com.timmons.srl.esriJsMap.geocodeAddress() in esriJsMap.js");
            
            _geocodeAddress(address, obj, callback);
            //console.log("Exit com.timmons.srl.esriJsMap.geocodeAddress() in esriJsMap.js");
        },
        addMarkers: function(markersJson) {
            //console.log("Enter com.timmons.srl.esriJsMap.addMarkers() in esriJsMap.js");
            
            _addMarkers(markersJson);
            //console.log("Exit com.timmons.srl.esriJsMap.addMarkers() in esriJsMap.js");
        },
        getAddress: function() {
            //console.log("Enter com.timmons.srl.esriJsMap.getAddress() in esriJsMap.js");
            
            return _getAddress();
            //console.log("Exit com.timmons.srl.esriJsMap.getAddress() in esriJsMap.js");
        },
        hasMarkers: function() {
            //console.log("Enter com.timmons.srl.esriJsMap.hasMarkers() in esriJsMap.js");
            
            if(_foregroundGraphic && _foregroundGraphic != null){
                return true;
            }                     
            
            if(_markers && _markers.length > 0){
                return true;
            }
            
            //console.log("Enter com.timmons.srl.esriJsMap.hasMarkers() in esriJsMap.js");
            return false;
        },        
        clear: function() {
            _clearMap();
        }
    };
};

function getSimpleMarkerSymbol(){
    
    var markerStyle = esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE;
    var lineStyle = esri.symbol.SimpleLineSymbol.STYLE_SOLID;
    var lineColor = new dojo.Color("black");
    var lineSymbol = new esri.symbol.SimpleLineSymbol(lineStyle, lineColor, 1);
    var fillColor = new dojo.Color("red");
    
    return new esri.symbol.SimpleMarkerSymbol(markerStyle, 10, lineSymbol, fillColor);
}

//        var originalLocation = new esri.geometry.Point(point.location.x, point.location.y);

//        var markerStyle = esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE;
//        var lineStyle = esri.symbol.SimpleLineSymbol.STYLE_SOLID;
//        var lineColor = new dojo.Color("white");
//        var lineSymbol = new esri.symbol.SimpleLineSymbol(lineStyle, lineColor, 1);
//        var fillColor = new dojo.Color([245, 128, 37, 1]);
//        var symbol = new esri.symbol.SimpleMarkerSymbol(markerStyle, 20, lineSymbol, fillColor);

//        var graphic = new esri.Graphic(
//            point.location,
//            symbol,
//            point.address,
//            infoTemplate
//        );

//        _map.graphics.add(graphic);
        
