﻿dojo.require("esri.virtualearth.VETiledLayer");

function LoadMapVars(map) {


    _latLngMarkLayer = new esri.layers.GraphicsLayer({ id: "latLngMarkLayer", displayOnPan: !dojo.isIE });
    _map.addLayer(_latLngMarkLayer);
    _latLngMarkLayer.hide();

    _lastPoiLayer = new esri.layers.GraphicsLayer({ id: "lasPoiLayer", displayOnPan: !dojo.isIE });
    _map.addLayer(_lastPoiLayer);
    _lastPoiLayer.hide();

    _weatherLayer = new esri.layers.GraphicsLayer({ displayOnPan: !dojo.isIE });
    map.addLayer(_weatherLayer);
    _weatherLayer.hide();

    _addressLayer = new esri.layers.GraphicsLayer({ id: "addressLayer", displayOnPan: !dojo.isIE });
    map.addLayer(_addressLayer);
    _addressLayer.hide();

    _mapTraffic = new esri.layers.GraphicsLayer({ displayOnPan: !dojo.isIE });
    map.addLayer(_mapTraffic);
    _mapTraffic.setOpacity(0.90);
    _mapTraffic.hide();

    _mapTrafficEvents = new esri.layers.GraphicsLayer({ displayOnPan: !dojo.isIE });
    map.addLayer(_mapTrafficEvents);
    _mapTrafficEvents.hide();

    _tweetsLayer = new esri.layers.GraphicsLayer({ displayOnPan: !dojo.isIE });
    map.addLayer(_tweetsLayer);
    _tweetsLayer.hide();

    dojo.connect(map, "onZoomEnd", ZoomEnd);
    dojo.connect(map, "onResize", MapResize);

    _toolbar = new esri.toolbars.Draw(map);
    _toolbar.lineSymbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color("#ff7000"), 2);
    _toolbar.fillSymbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color("#ff7000"), 2), new dojo.Color([255, 112, 0, 0.25]));

    /*
    a = document.getElementById("wazeContainer");
    _map.__root.appendChild(a);*/

    CreateArrow();
    
    map.resize();
    map.reposition();    

    map.centerAndZoom(new esri.geometry.Point(-78.31911076002143, -1.789589767301139, map.spatialReference), 4);

    if (_fromPermalink) {
        DrawPointFromPermalink();
    }
    else {
        if (_latLngPermalink)
            DrawPointFromLatLngPermalink();
    }
    
    LoadWazeTraffic();
    LoadWazeEvents();
    LoadWeatherEvents();
    LoadTweets();

    setInterval("LoadWazeTraffic()", 300000);
    setInterval("LoadWazeEvents()", 400000);
    setInterval("LoadWeatherEvents()", 500000);
    setInterval("LoadTweets()", 600000);
    SetScaleBar(map.extent, map.width);
    
    _autosuggest = new lw.AutoSuggest();
    _autosuggest.InitAutoSuggest({ cityField: "txtAdvancedSearchCity", streetField: "txtSearchAddressStreet", intersectionField: "txtSearchAddressIntersection", placeField: "txtSearchPOIName" });
        
    //_getMyLocation = setInterval("GetMyLocation()", 2000);
}

var _getMyLocation;
function GetMyLocation() {

    if (!_gUniqueTrack.mylocation) {
        _gaq.push(['_trackEvent', 'Eventos Unicos', 'Mi Ubicación']);
        _gUniqueTrack.mylocation = true;
    }

    ShowLoading();

    if (!window.google || !window.google.gears) {
        HideLoading();
        /*var message = 'To enable fast client-side search of this website '
                        + 'please install Gears';*/
        var url = 'http://gears.google.com/?action=install';
                      /*+ '&message=' + encodeURIComponent(message)
                      + '&return=' + encodeURIComponent(window.location.href);*/
        ShowMsgBox('Para utilizar esta funcionalidad primero debes instalar Google Gears.<br /><br /><a style=\"color:#ccc;\" href="' + url + '" target=\"_blank\">Instala Google Gears aquí !</a>');
        return false;
    }
    else {
        _geo = google.gears.factory.create('beta.geolocation');
        _geo.getCurrentPosition(UpdateGGPosition, GogleGearsHandleError);
    }
    //clearInterval(_getMyLocation);
}

function MapResize(extent, height, width) {
    SetScaleBar(extent, _map.width);
}

function ZoomEnd(extent, zoomFactor, anchor, level) {
    SetScaleBar(extent, _map.width);
    /*
    if (level > 8) {
        if (_weatherLayer.visible) {
            
            dojo.style("infoTrafficEvent", {
                "display": "none"
            });

            _weatherLayer.hide();            
        }
            
        dojo.removeClass("btnWeather", "btnWeather_over");
        dojo.removeClass("btnWeather", "btnWeather");
        dojo.addClass("btnWeather", "btnWeather_disabled");


    }
    else {


        dojo.removeClass("btnWeather", "btnWeather_disabled");
        dojo.addClass("btnWeather", "btnWeather");


    }*/
}

function CreateArrow() {
    var arrow = document.createElement("div");
    arrow.setAttribute("id", "apiNorthArrow-" + _map.id);
    _map.__root.appendChild(arrow);
    dojo.addClass("apiNorthArrow-" + _map.id, "north-arrow");
    dojo.style("apiNorthArrow-" + _map.id, {
        "position": "absolute",
        "top": "10px",
        "left": "10px"
    });
}

function GoPico(c) {
    if (c) {
        _picoYPlacaService.setOpacity(0.4);
        
        var today = new Date()
        thisDay = today.getDay()
        if (thisDay > 0 && thisDay < 6) {
            dojo.byId("pp" + thisDay.toString()).style.color = "#ABC600";
            dojo.byId("pp" + thisDay.toString()).style.fontWeight = "bold";
        }

        if ($.browser.msie) {
            dojo.byId("picoPlacaContainer").style.display = "block";            
        }
        else
            $("#picoPlacaContainer").toggle(200);
    }
    else {
        if ($.browser.msie)
            dojo.byId("picoPlacaContainer").style.display = "none";            
        else
            $("#picoPlacaContainer").toggle(200);
        _picoYPlacaService.setOpacity(0.0);
    }
}

function HideTrafficLegend() {
    $("#trafficLegend").animate({ opacity: "0" }, { duration: 300, complete: function () { $("#trafficLegend").hide(); } });
}


function HideCoverageNote() {
    $("#coverageNote").animate({ opacity: "0" }, { duration: 300, complete: function () { $("#coverageNote").hide(); } });
}

function GoCoverage(c) {
    if (c) {
        _ecuadorMapService3G.setOpacity(0.5);
        //if (_currentMapType == "ESRI")
        $("#coverageNote").show(0, function () {
            $("#coverageNote").css("opacity", 1);
            $("#coverageNote").position({
                of: $("#content"),
                my: "right top",
                at: "right top",
                collision: "none",
                offset: "-20 65"
            });
        });
        setTimeout('HideCoverageNote()', 10000);
    }
    else {
        _ecuadorMapService3G.setOpacity(0.0);
        $("#coverageNote").hide();
    }
}

function GoWazeTraffic(c) {
    GoTraffic(c);
}

var BingToken = "Akjwzq7VvENFp8J1IzbZmhSW6B--MutrFTcR895ww5Ti8zQm2_aSZtQK8wsGzZ3X";

var _currentMapType = "ESRI";

function ReloadLayers(map) {

    _latLngMarkLayer = new esri.layers.GraphicsLayer({ id: "latLngMarkLayer", displayOnPan: !dojo.isIE });
    map.addLayer(_latLngMarkLayer);

    for (k = 0; k < _lastLatLng.length; k++) {
        _latLngMarkLayer.add(new esri.Graphic(GetConvertedPoint(_lastLatLng[k].graphic.geometry), new esri.symbol.PictureMarkerSymbol("images/marker.png", 68, 68))
            .setAttributes(_lastLatLng[k].attr));
    }

    if (_lastLatLng.length > 0)
        _latLngMarkLayer.show();

    for (k = 0; k < _currentGraphics.length; k++) {
        var icon = "images/markers/" + (k + 1).toString() + ".png";
        var userIcon = "images/user_poi.png";
        var i = icon;
        if (dojo.byId('userEmail').value != "")
            if (dojo.byId('userEmail').value == _currentGraphics[k].attr.pOwnerEmail)
                i = userIcon;
        _map.graphics.add(new esri.Graphic(GetConvertedPoint(_currentGraphics[k].graphic.geometry), new esri.symbol.PictureMarkerSymbol(i, 68, 68))        
            .setAttributes(_currentGraphics[k].attr));
    }

    if (_currentGraphics.length > 0)
        _onPOIMouseClick = dojo.connect(_map.graphics, "onClick", ShowPOIInfoWindowFromMapPoint);

    _lastPoiLayer = new esri.layers.GraphicsLayer({ id: "lasPoiLayer", displayOnPan: !dojo.isIE });
    map.addLayer(_lastPoiLayer);
        
    for (k = 0; k < _lastPoiGraphics.length; k++) {
        var icon = "images/marker.png";
        var userIcon = "images/user_poi.png";
        var i = icon;
        if (dojo.byId('userEmail').value != "")
            if (dojo.byId('userEmail').value == _lastPoiGraphics[k].attr.pOwnerEmail)
                i = userIcon;
        _lastPoiLayer.add(new esri.Graphic(GetConvertedPoint(_lastPoiGraphics[k].graphic.geometry), new esri.symbol.PictureMarkerSymbol(i, 68, 68))
            .setAttributes(_lastPoiGraphics[k].attr));
    }

    if (_lastPoiGraphics.length > 0) {
        _onPOIMouseClick = dojo.connect(_map.graphics, "onClick", ShowPOIInfoWindowFromMapPoint);
        _lastPoiLayer.show();
    }
    else
        _lastPoiLayer.hide();

    _weatherLayer = new esri.layers.GraphicsLayer({ displayOnPan: !dojo.isIE });
    map.addLayer(_weatherLayer);
    
    if (dojo.hasClass("btnWeather", "btnWeather_over"))
        _weatherLayer.show();
    else
        _weatherLayer.hide();

    LoadWeatherEvents();

    _addressLayer = new esri.layers.GraphicsLayer({ id: "addressLayer", displayOnPan: !dojo.isIE });
    map.addLayer(_addressLayer);

    if (_currentAddressLayer) {
        var g = new esri.Graphic(GetConvertedPoint(_currentAddressLayer.graphic.geometry), ADDRESS_PUSHPING_SYMBOL).setInfoTemplate(_currentAddressLayer.info).setAttributes(_currentAddressLayer.attr);
        _addressLayer.add(g);
    }
    else
        _addressLayer.hide();

    dojo.disconnect(_onAddressPushpinClick);
    _onAddressPushpinClick = dojo.connect(_addressLayer, "onClick", ShowAddressInfoWindowFromMapPoint);

    _mapTraffic = new esri.layers.GraphicsLayer({ displayOnPan: !dojo.isIE });
    map.addLayer(_mapTraffic);
    _mapTraffic.setOpacity(0.90);

    _mapTrafficEvents = new esri.layers.GraphicsLayer({ displayOnPan: !dojo.isIE });
    map.addLayer(_mapTrafficEvents);

    if (dojo.hasClass("btnWaze", "btnWaze_over")) {
        _mapTraffic.show();
        _mapTrafficEvents.show();
    }
    else {
        _mapTraffic.hide();
        _mapTrafficEvents.hide();
    }

    LoadWazeTraffic();
    LoadWazeEvents();
        
    _toolbar = new esri.toolbars.Draw(map);
    _toolbar.lineSymbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color("#ff7000"), 2);
    _toolbar.fillSymbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color("#ff7000"), 2), new dojo.Color([255, 112, 0, 0.25]));

    _tweetsLayer = new esri.layers.GraphicsLayer({ displayOnPan: !dojo.isIE });
    map.addLayer(_tweetsLayer);

    if (dojo.hasClass("btnTweets", "btnTweets_over"))
        _tweetsLayer.show();
    else
        _tweetsLayer.hide();

    LoadTweets();

    CreateArrow();
    
}

var _currentGraphics;
var _currentAddressLayer;
var _lastPoiGraphics;
var _lastLatLng;
function GoSatelite(c) {
    
    var extent = _map.extent;

    _currentGraphics = new Array();
    for (i = 0; i < _map.graphics.graphics.length; i++) {
        if (_currentMapType == "BING") {
            _map.graphics.graphics[i].geometry = esri.geometry.webMercatorToGeographic(_map.graphics.graphics[i].geometry);
        }
        _currentGraphics.push({ graphic: _map.graphics.graphics[i], attr: _map.graphics.graphics[i].attributes });
    }

    _lastPoiGraphics = new Array();
    if (_lastPoiLayer.visible) {        
        for (i = 0; i < _lastPoiLayer.graphics.length; i++) {
            if (_currentMapType == "BING") {
                _lastPoiLayer.graphics[i].geometry = esri.geometry.webMercatorToGeographic(_lastPoiLayer.graphics[i].geometry);
            }
            _lastPoiGraphics.push({ graphic: _lastPoiLayer.graphics[i], attr: _lastPoiLayer.graphics[i].attributes });
        }
    }
    
    _lastLatLng= new Array();
    if (_latLngMarkLayer.visible) {
        for (i = 0; i < _latLngMarkLayer.graphics.length; i++) {
            if (_currentMapType == "BING") {
                _latLngMarkLayer.graphics[i].geometry = esri.geometry.webMercatorToGeographic(_latLngMarkLayer.graphics[i].geometry);
            }
            _lastLatLng.push({ graphic: _latLngMarkLayer.graphics[i], attr: _latLngMarkLayer.graphics[i].attributes });
        }
    }

    if (_addressLayer.visible) {
        if (_currentMapType == "BING") {
            _addressLayer.graphics[0].geometry = esri.geometry.webMercatorToGeographic(_addressLayer.graphics[0].geometry);
        }
        _currentAddressLayer = { graphic: _addressLayer.graphics[0], attr: _addressLayer.graphics[0].attributes, info: _addressLayer.graphics[0].infoTemplate };
    }
    else
        _currentAddressLayer = null;

    // Here before making the destroy take address or pois results into temp vars.

    if (_map) _map.destroy();

    HideMeasureTool();
    
    DeactivateAddPointOnMap();

    if (c == true) {
        
        $("#bingLogoTrans").show();
        
        HideScaleBar();
        
        _currentMapType = "BING";
        _map = extent ? new lw.Map("map", { displayGraphicsOnPan: !dojo.isIE, extent: extent.spatialReference.wkid != 102100 ? esri.geometry.geographicToWebMercator(extent) : extent }) : new lw.Map("map", { displayGraphicsOnPan: !dojo.isIE });
            veTileLayer = new esri.virtualearth.VETiledLayer({
            bingMapsKey: BingToken,
            mapStyle: esri.virtualearth.VETiledLayer.MAP_STYLE_AERIAL
        });

        _map.addLayer(veTileLayer);

        if (!_map.loaded) {
            dojo.disconnect(testconnect);
            dojo.connect(_map, "onLoad", ReloadLayers);
        }
        else
            ReloadLayers(_map);
        
    }
    else {

        $("#bingLogoTrans").hide();

        ShowScaleBar();
        
        _currentMapType = "ESRI";
        _map = extent ? new lw.Map("map", { displayGraphicsOnPan: !dojo.isIE, extent: extent.spatialReference.wkid != 4326 ? esri.geometry.webMercatorToGeographic(extent) : extent }) : new lw.Map("Map", { displayGraphicsOnPan: !dojo.isIE });

        _map.addLayer(_ecuadorMapService);
        _map.addLayer(_ecuadorMapService3G);
        _map.addLayer(_picoYPlacaService);

        if (!_map.loaded) {
            dojo.disconnect(testconnect);
            dojo.connect(_map, "onLoad", ReloadLayers);
        }
        else
            ReloadLayers(_map);

    }

}

//Function that sets the correct extent to view all points from the collection into the map.
function SetLevel(pointCollection) {
    var initialExtent = pointCollection.getExtent();
    var center = initialExtent.getCenter();
    var tileInfo = _ecuadorMapService.tileInfo;    

    for (var j = tileInfo.lods.length - 1; j >= 0; j--) {
        var resolution = tileInfo.lods[j].resolution;
        var xMin = center.x - (((_map.width / 2) - 210) * resolution);
        var yMin = center.y - ((_map.height / 2) * resolution);
        var xMax = center.x + ((_map.width / 2) * resolution);
        var yMax = center.y + ((_map.height / 2) * resolution);
        var extent = new esri.geometry.Extent(xMin, yMin, xMax, yMax);

        var isInside = false;
        for (k = 0; k < pointCollection.points.length; k++) {
            var point = new esri.geometry.Point(pointCollection.points[k][0], pointCollection.points[k][1]);
            //var point = pointCollection.points[k];
            isInside = IsInsideExtent(point, extent);
            if (!isInside) break;
        }

        if (isInside) {
            //_map.centerAndZoom(center, tileInfo.lods[j].level);

            center = GetConvertedPoint(center);
            level = GetConvertedLevel(tileInfo.lods[j].level);

            _map.centerAndZoom(center, level);
            break;
        }
    }
}

//Function that verifies if a point is inside of a specific extent.
function IsInsideExtent(point, extent) {
    if ((point.x >= extent.xmin && point.x <= extent.xmax) && (point.y >= extent.ymin && point.y <= extent.ymax))
        return true;
    else
        return false;
}

function SetLevelAllFunctions() {
    SetLevel(_EVCZpointsColl.getValue());
}

//******************************************************************************
//FUNCTIONS TO HANDLE THE MAP PRINT
//*******************************************************************************

function PrintMap() {
    _gaq.push(['_trackEvent', 'Eventos Recurrentes', 'Impresión de Mapa']);
    if (_currentMapType == "ESRI") {
        var center = _map.extent.getCenter();
        var mapCenter = center.y + "," + center.x;
        var infoPoints = GetPointsToPrint();

        var currLevel = _map.getLevel();
        var callback = "infoPoints::" + (infoPoints.length > 0 ? infoPoints.substr(0, infoPoints.length - 3) : infoPoints) +
                 "|mapSize::" + _map.width + "x" + _map.height +
                 "|mapLevel::" + (currLevel + ((16 - currLevel) - currLevel)) +
                 "|center::" + mapCenter
        PageMethods.PrintMap(callback, ShowPrintWindow);
        return false;
    }
    else
        ShowMsgBox('Funcionalidad disponible solo para el mapa de Location World.');
}

function GetPointsToPrint() {
    
    var infoPoints = "";
    
    if (_addressLayer.graphics.length == 1) {
        infoPoints = hosturl + "/images/marker.png" + "," + +_addressLayer.graphics[0].geometry.y + "," + _addressLayer.graphics[0].geometry.x + ".*.";
    }
    
    for (i = 0; i < _map.graphics.graphics.length; i++)
        infoPoints += hosturl + _map.graphics.graphics[i].symbol.url + "," + _map.graphics.graphics[i].geometry.y + "," + _map.graphics.graphics[i].geometry.x + ".*.";

    if (_weatherLayer.visible) {
        for (i = 0; i < _weatherLayer.graphics.length; i++) {
            if (IsInsideExtent(_weatherLayer.graphics[i].geometry, _map.extent))
                infoPoints += _weatherLayer.graphics[i].symbol.url + "," + _weatherLayer.graphics[i].geometry.y + "," + _weatherLayer.graphics[i].geometry.x + ".*.";
        }
    }
    /*
    if (_mapTrafficEvents.visible) {
        for (i = 0; i < _mapTrafficEvents.graphics.length; i++) {
            if (IsInsideExtent(_mapTrafficEvents.graphics[i].geometry, _map.extent))
                infoPoints += hosturl + _mapTrafficEvents.graphics[i].symbol.url + "," + _mapTrafficEvents.graphics[i].geometry.y + "," + _mapTrafficEvents.graphics[i].geometry.x + ".*.";
        }
    }

    if (_tweetsLayer.visible) {
        for (i = 0; i < _tweetsLayer.graphics.length; i++) {
            if (IsInsideExtent(_tweetsLayer.graphics[i].geometry, _map.extent))
                infoPoints += hosturl + _tweetsLayer.graphics[i].symbol.url + "," + _tweetsLayer.graphics[i].geometry.y + "," + _tweetsLayer.graphics[i].geometry.x + ".*.";
        }
    }*/

    return infoPoints;
}

function ShowPrintWindow(results) {
    if (results != null) {
        if (results.indexOf("Redirect") >= 0) {
            window.open("Print.aspx", "", "height=" + (_map.height + 151) + ",width=" + (_map.width+2) + ", scrollbars=no");
        }
    }
}

//******************************************************************************
//FUNCTIONS TO HANDLE THE EMAILS SENT
//*******************************************************************************

function ShowMailPage() {
    _gaq.push(['_trackEvent', 'Eventos Recurrentes', 'Envio de Mapa']);
    if (_currentMapType == "ESRI") {
        dojo.xhrGet({
            url: "MailPage.htm",
            handleAs: "text",
            handle: function (data, args) {
                if (typeof data == "error")
                    alert("error");
                else {
                    dojo.byId("divWindow").innerHTML = data;
                    dojo.byId("divWindow").style["display"] = "block";
                    dojo.byId("divTransparency2").style["display"] = "block";
                }
            }
        });
        return false;
    }
    else
        ShowMsgBox('Funcionalidad disponible solo para el mapa de Location World.');


}

function CancelMailForm() {
    dojo.byId("divWindow").innerHTML = "";
    dojo.byId("divWindow").style["display"] = "none";
    dojo.byId("divTransparency2").style["display"] = "none";

    return false;
}

function SendMail() {
    
    var mailTo = document.forms[0]["txtMailTo"].value.trim();
    var mailFrom = document.forms[0]["txtMailFrom"].value.trim();    
    var mailAsunto = document.forms[0]["txtAsunto"].value.trim();
    var mailComment = document.forms[0]["txtComment"].value.trim();

    mailTo = (mailTo.charAt(mailTo.length - 1) == ",") ? mailTo.substr(0, mailTo.length - 1) : mailTo;
    var mailToRegEx = /^([,]\s*[a-zA-Z0-9._-]+([+][a-zA-Z0-9._-]+){0,1}[@][a-zA-Z0-9._-]+[.][a-zA-Z]{2,6})+$/;

    //I put the comma first to coupling the first email from the list with its reg expression.  
    if (!mailToRegEx.test("," + mailTo)) {
        ShowMsgBox("Las direcciones de destino no se encuentra en el formato correcto.");
        return false;
    }

    mailFrom = (mailFrom.charAt(mailFrom.length - 1) == ",") ? mailFrom.substr(0, mailFrom.length - 1) : mailFrom;
    var mailFromRegEx = /^[a-zA-Z0-9._-]+([+][a-zA-Z0-9._-]+){0,1}[@][a-zA-Z0-9._-]+[.][a-zA-Z]{2,6}$/;
    if (!mailFromRegEx.test(mailFrom)) {
        ShowMsgBox("La dirección del remitente no se encuentra en el formato correcto.");
        return false;
    }

    var center = _map.extent.getCenter();
    var mapCenter = center.y + "," + center.x;
    var infoPoints = GetPointsToPrint();

    var currLevel = _map.getLevel();

    //dojo.byId("SendMailButton").style["display"] = "none";

    var callback = "from::" + mailFrom +
                 "|to::" + mailTo +
                 "|name::" + name +
                 "|subject::" + mailAsunto +
                 "|comment::" + mailComment +
                 "|infoPoints::" + (infoPoints.length > 0 ? infoPoints.substr(0, infoPoints.length - 3) : infoPoints) +
                 "|mapSize::" + _map.width + "x" + _map.height +
                 "|mapLevel::" + (currLevel + ((16 - currLevel) - currLevel)) +
                 "|center::" + mapCenter;
    PageMethods.SendMapByMail(callback, ShowResponseSendMail);
    ShowLoading();
    return false;
}

function ShowResponseSendMail(results) {
    if (results != null) {
        dojo.byId("divWindow").style["display"] = "none";
        dojo.byId("divTransparency2").style["display"] = "none";
        HideLoading();
        ShowMsgBox(results);        
    }
}

//Function to load the scale bar on the map.
function SetScaleBar(mapExtent, mapWidth) {    
    var scale = ((mapExtent.xmax - mapExtent.xmin) / mapWidth) * 96;
    var dvScaleMiles = dojo.byId("dvScaleMiles");
    var dvScaleKM = dojo.byId("dvScaleKM");
    if (dvScaleMiles == null && dvScaleKM == null) return;

    var units = _map.getLayer(_map.layerIds[0]).units;
    var miles, km;
    if (units == "esriFeet") {
        miles = scale / 5280;
        km = scale * 0.3048 / 1000;
    }
    if (units == "esriMeters") {
        miles = scale / 0.3048 / 5280;
        km = scale / 1000;
    }
    if (units == "esriDecimalDegrees") {
        miles = (scale * 111319.46) / 0.3048 / 5280;
        km = (scale * 111319.46) / 1000;
    }
    dvScaleMiles.innerHTML = miles.toFixed(2) + " millas.";
    dvScaleKM.innerHTML = km.toFixed(2) + " km.";
}



/*###newcode */

var _isAddModeActive = false;

function DrawPointAtLatLon(lat, lon, zoom) {

    _latLngMarkLayer.clear();

    //$("input[id*=hddLat]").val(lat);
    //$("input[id*=hddLon]").val(lon);

    //$(".feedbackcoordinates").html("Latitud: " + lat.toString().substr(0, lat.toString().indexOf('.') + 1) + lat.toString().substr(lat.toString().indexOf('.') + 1, 5) + ", Longitud: " + lon.toString().substr(0, lon.toString().indexOf('.') + 1) + lon.toString().substr(lon.toString().indexOf('.') + 1, 5));

    //var p = GetConvertedPoint(new esri.geometry.Point(parseFloat(lon), parseFloat(lat), _map.spatialReference));
    var p = new esri.geometry.Point(parseFloat(lon), parseFloat(lat), _map.spatialReference);

    var icon = "images/marker.png";

    var myAttributes = { pID: -1, pLong: lon, pLat: lat };
    var g = new esri.Graphic(p, new esri.symbol.PictureMarkerSymbol(icon, 68, 68)).setAttributes(myAttributes);

    _latLngMarkLayer.add(g);

    dojo.disconnect(_cc);
    dojo.disconnect(_dd);

    if (_ff) dojo.disconnect(_ff);
    _ff = dojo.connect(_latLngMarkLayer, "onClick", ShowCustomAddressInfoWindow);

    if (zoom)
        _map.centerAndZoom(p, GetConvertedLevel(15));

    _map.resize();
    _map.reposition();

}

function btnShareCurrentLocation(lat, lng) {
    var email = $("#sh_email").val();
    var name = $("#sh_name").val();

    if (name == "") {
        alert('Debes ingresar tu nombre para poder compartir esta dirección.');
        return;
    }

    if (IsValidEmail(email)) {
        PageMethods.SendLatLngByEmail(lat, lng, name, email, ProccessSendLatLngByEmail);
    }
    else {
        alert('Debes ingresar un email válido.');
        return;
    }
}

function ProccessSendLatLngByEmail(result) {
    alert(result);
    _map.infoWindow.hide();
}

function ShowCustomAddressInfoWindow(event) {    
    var graphic = event.graphic;
    var html = "" +
        "<div style=\"font-size:10px; padding-left:5px; font-family:Verdana;\">" +
            "<div>Tu nombre:</div>" +
            "<div><input style=\"border: 1px solid #ccc; width:180px;\" id=\"sh_name\" /></div>" +
            "<div style=\"margin-top:5px;\">Email de destino:</div>" +
            "<div><input style=\"border: 1px solid #ccc; width:180px;\" id=\"sh_email\" /></div>" +
            "<div style=\"text-align:right; margin-top:5px;\">" +
                "<div class=\"shareLatLngButton\" onclick=\"btnShareCurrentLocation(" + graphic.geometry.y + "," + graphic.geometry.x + ");\"></div>" +
            "</div>" +
        "</div>";
    _map.infoWindow.resize(250, 150);
    _map.infoWindow.setTitle("Compartir Ubicación").setContent(html);
    _map.infoWindow.show(_map.toScreen(graphic.geometry), _map.getInfoWindowAnchor(_map.toScreen(graphic.geometry)));

}

function IsPoiAddition(event) {
    if (event.button != 2) {
        if (_isAddModeActive == true) {
            $("#pushpintip").hide();

            //var p = _map.toMap(new esri.geometry.Point((event.pageX - 1), (event.pageY - 9)));
            var p = _map.toMap(new esri.geometry.Point((event.pageX - 1 - $("#map").position().left), (event.pageY - 9 - $("#map").position().top)));

            DrawPointAtLatLon(p.y, p.x, true);

            //$("#pushpinbox").css("opacity", 0.85);
            _isAddModeActive = false;
            //$("#map_container").css("cursor", "default");
            _map.setMapCursor('default');
            _map.enableMapNavigation();
        }
    }
}

function MapOnMouseMove(event) {
    if (_isAddModeActive) {
        var x = event.clientX - 15;
        var y = event.clientY - 43;
        $("#pushpintip").show(0, function () {
            //dojo.byId("pushpintip").style.left = event.clientX + "px";
            //dojo.byId("pushpintip").style.top = event.clientY + "px";
            $(this).css('left', x);
            $(this).css('top', y);
        });
    }
}
var _cc = null;
var _dd = null;
var _ff = null;
function AddPushPin() {

    if (_isAddModeActive == false) {
        _latLngMarkLayer.show();
        if (_cc)
            dojo.disconnect(_cc);
        if (_dd) dojo.disconnect(_dd);
        _cc = dojo.connect(_map, "onMouseMove", MapOnMouseMove);
        _dd = dojo.connect(_map, "onMouseUp", IsPoiAddition);
        //$("#map_container").css("cursor", "none");
        if ($.browser.msie) {
            $("#pushpintip").css("cursor", "url(images/invisible.cur),auto");
            _map.setMapCursor("url(images/invisible.cur),auto");
        }
        else {
            $("#pushpintip").css("cursor", "none");
            _map.setMapCursor('none');
        }


        _isAddModeActive = true;

        _map.disableMapNavigation();

        //dojo.disconnect(_onNewPointMouseDown);
        //dojo.disconnect(_onNewPointMouseDrag);
        //dojo.disconnect(_onNewPointMouseUp);

        //$("input[id*=hddLat]").val("0");
        //$("input[id*=hddLon]").val("0");
        //$(".feedbackcoordinates").html("Latitud: 0, Longitud: 0");

        //$("#pushpinbox").css("opacity", 0.35);

        if (_latLngMarkLayer.graphics.length > 0)
            _latLngMarkLayer.clear();

    }
    else {
        dojo.disconnect(_cc);
        //$("#pushpinbox").css("opacity", 0.85);
        _isAddModeActive = false;
        _map.enableMapNavigation();
        $("#pushpintip").hide();
        //$("#map_container").css("cursor", "default");
        _map.setMapCursor('default');
        _latLngMarkLayer.hide();
    }

}

