﻿var _evtPOIAddOnMouseMove = null;
var _evtPOIOnMouseUp = null;
var _evtPOIAddOnMouseOut = null;
var _evtPOIAddOnPanStart = null;
var _evtPOIAddOnPanEnd = null;

var _beingLoadedToModify = false;

var _addPOICurrentStep = 1;

var _addPOIAcceptTerms = false;

// Permalink Info

var _fromPermalink = false;
var _permalinkId = 0;
var _permalinkLat = 0;
var _permalinkLong = 0;
var _permalinkOwnerEmail = "";
var _updateZoomOnPermalink = null;
var _updateZoomOnLatLngPermalink = null;

var _latLngPermalink = false; 

function SetPermalinkLatLngInfo(lat, lng) {
    _latLngPermalink = true;
    _permalinkLat = lat;
    _permalinkLong = lng;
}

function SetPermalinkInfo(id, lat, lng, owner) {
    _permalinkId = id;
    _permalinkLat = lat;
    _permalinkLong = lng;
    _permalinkOwnerEmail = owner;
    _fromPermalink = true;
}
var _permalinkPoint = null;
function DrawPointFromPermalink() {

    _permalinkPoint = new esri.geometry.Point(parseFloat(_permalinkLong), parseFloat(_permalinkLat), _map.spatialReference);

    var icon = "images/marker.png";
    var userIcon = "images/user_poi.png";

    var i = icon;

    if (dojo.byId('userEmail').value != "")
        if (dojo.byId('userEmail').value == _permalinkOwnerEmail)
            i = userIcon;

    var myAttributes = { pID: _permalinkId, pLong: _permalinkLong, pLat: _permalinkLat, pOwnerEmail: _permalinkOwnerEmail };    
    var g = new esri.Graphic(_permalinkPoint, new esri.symbol.PictureMarkerSymbol(i, 68, 68))
        .setAttributes(myAttributes);

    _map.graphics.add(g);

    if (_onNewPointClick == null && _onPOIMouseClick == null)
        _onNewPointClick = dojo.connect(_map.graphics, "onClick", ShowPOIInfoWindowFromMapPoint);

    _updateZoomOnPermalink = setInterval("UpdateZoomOnPermalink()", 3000);
}

var _permalinkLatLngPoint = null;
function DrawPointFromLatLngPermalink() {
    _permalinkLatLngPoint = new esri.geometry.Point(parseFloat(_permalinkLong), parseFloat(_permalinkLat), _map.spatialReference);

    var icon = "images/marker.png";

    var myAttributes = { pID: -1, pLong: _permalinkLong, pLat: _permalinkLat, pOwnerEmail: "" };
    var g = new esri.Graphic(_permalinkLatLngPoint, new esri.symbol.PictureMarkerSymbol(icon, 68, 68))
        .setAttributes(myAttributes);

    _map.graphics.add(g);

/*    if (_onNewPointClick == null && _onPOIMouseClick == null)
        _onNewPointClick = dojo.connect(_map.graphics, "onClick", ShowPOIInfoWindowFromMapPoint);*/

    _updateZoomOnLatLngPermalink = setInterval("UpdateZoomOnLatLngPermalink()", 3000);

}

function UpdateZoomOnLatLngPermalink() {
    _map.centerAndZoom(_permalinkLatLngPoint, 15);
    clearInterval(_updateZoomOnLatLngPermalink);
}

function UpdateZoomOnPermalink() {
    _map.centerAndZoom(_permalinkPoint, 15);
    clearInterval(_updateZoomOnPermalink);
}

// Activate/Desactivate POI Add

function ActivateAddPointOnMap() {
    var map = _map;
    DeactivateAddPointOnMap();
    _evtPOIAddOnMouseMove = dojo.connect(map, "onMouseMove", POIOnMouseMove);
    _evtPOIOnMouseUp = dojo.connect(map, "onMouseUp", POIOnMouseUp);
    _evtPOIAddOnMouseOut = dojo.connect(map, "onMouseOut", POIOnMouseOut);
    _evtPOIAddOnPanStart = dojo.connect(map, "onPanStart", POIOnPanStart);
    _evtPOIAddOnPanEnd = dojo.connect(map, "onPanEnd", POIOnPanEnd);

    dojo.removeClass("btnActivateAddMode", "btnActivateAddMode");
    dojo.addClass("btnActivateAddMode", "btnActivateAddMode_disabled");

    dojo.removeClass("btnDeactivateAddMode", "btnDeactivateAddMode_disabled");
    dojo.addClass("btnDeactivateAddMode", "btnDeactivateAddMode");

}

function DeactivateAddPointOnMap() {
    dojo.disconnect(_evtPOIAddOnMouseMove);
    dojo.disconnect(_evtPOIOnMouseUp);
    dojo.disconnect(_evtPOIAddOnMouseOut);
    dojo.disconnect(_evtPOIAddOnPanStart);
    dojo.disconnect(_evtPOIAddOnPanEnd);

    dojo.removeClass("btnActivateAddMode", "btnActivateAddMode_disabled");
    dojo.addClass("btnActivateAddMode", "btnActivateAddMode");

    dojo.removeClass("btnDeactivateAddMode", "btnDeactivateAddMode");
    dojo.addClass("btnDeactivateAddMode", "btnDeactivateAddMode_disabled");

}

function ShowAddPOITip(event) {
    if (event != null) {
        var ny = event.clientY + 10;
        var nx = event.clientX + 10;

        dojo.style("add_icon", {
            "display": "block",
            "position": "absolute",
            "top": ny + "px",
            "left": nx + "px"
        });
    }
}

function HideAddPOITip(event) {
    dojo.style("add_icon", {
        "display": "none"
    });
}

function POIOnPanStart(event) {
    if(_evtPOIAddOnMouseMove)
        HideAddPOITip(event);
}

function POIOnPanEnd(event) {
}

function POIOnMouseOut(event) {
    if (_evtPOIAddOnMouseMove)
        HideAddPOITip(event);
}

function POIOnMouseMove(event) {
    ShowAddPOITip(event);
}

// This function get City and Address based on the poi lat and long

function LoadCityAndStreetInfo(result) {
    /*if (result.City == null && result.City != "") {
        dojo.byId("addPOICityName").innerHTML = "No se logro obtener información de ciudad y/o dirección en la ubicación seleccionada.";
        dojo.byId("addPOIAddress").innerHTML = "";
    }
    else {*/

        dojo.byId("addPOICityName").innerHTML = result.City + ", ";

        var m = "";
        var i = "";
        var address = "";

        if (result.MainStreet != null)
            if (result.MainStreet.MainName != null)
                if (result.MainStreet.MainName != "")
                    m = result.MainStreet.MainName;

        if (result.Intersection != null)
            if (result.Intersection.MainName != null)
                if (result.Intersection.MainName != "")
                    i = result.Intersection.MainName;

        if (m != "") {
            address = m;

            if (i != "")
                address += " y " + i;
        }
        else {
            if (i != "")
                address = i;
        }

        if (m == "" && i == "")
            address = "No se pudo calcular una dirección para la ubicación de su comercio."

        dojo.byId("addPOIAddress").innerHTML = address;
    //}
}

// Start add poi flow
var _cityId = -1;
function POIOnMouseUp(e) {
    
    if (e.button == 2) {

        if (!_gUniqueTrack.addpoitry) {
            _gaq.push(['_trackEvent', 'Eventos Unicos', 'Intento Publicacion de Puntos']);
            _gUniqueTrack.addpoitry = true;
        }

        var mp = e.mapPoint;

        var objGeoprocessing = new lw.Geoprocessing();
        objGeoprocessing.ReverseGeocode(mp.x, mp.y,
            function (result) {
                if (result.City) {
                    PageMethods.GetCityId(result.City, function (r) {
                        if (r != -1) {
                            _cityId = r;
                            _poi = null;

                            CleanAddPOIForm();
                            ShowAddPOIWindow();

                            if (_addPOICurrentStep != 1) {
                                HideAddPOIStep(_addPOICurrentStep);
                                _addPOICurrentStep = 1;
                                ShowAddPOIStep(_addPOICurrentStep);
                            }

                            dojo.byId('poiLat').value = mp.y;
                            dojo.byId('poiLong').value = mp.x;

                            dojo.byId('btnAddPOIPrevious').style.display = "none";
                            dojo.byId('btnAddPOISave').style.display = "none";
                            dojo.byId('btnAddPOINext').style.display = "block";

                            dojo.byId('fileAddPOIPhoto1Container').innerHTML = "<iframe id=\"ifr\" marginheight=\"0\" marginwidth=\"0\" frameborder=\"0\" scrolling=\"none\" width=\"210\" height=\"45\" src=\"web_controls/upload.imgs.aspx?hdd=fileAddPOIPhoto1&u=&path=" + dojo.byId('uploadPath').value + "\"></iframe>";
                            dojo.byId('fileAddPOIPhoto2Container').innerHTML = "<iframe id=\"ifr\" marginheight=\"0\" marginwidth=\"0\" frameborder=\"0\" scrolling=\"none\" width=\"210\" height=\"45\" src=\"web_controls/upload.imgs.aspx?hdd=fileAddPOIPhoto2&u=&path=" + dojo.byId('uploadPath').value + "\"></iframe>";
                            dojo.byId('fileAddPOILogoContainer').innerHTML = "<iframe id=\"ifr\" marginheight=\"0\" marginwidth=\"0\" frameborder=\"0\" scrolling=\"none\" width=\"210\" height=\"45\" src=\"web_controls/upload.imgs.aspx?hdd=fileAddPOILogo&u=&path=" + dojo.byId('uploadPath').value + "\"></iframe>";

                            GetGroups();

                            LoadCityAndStreetInfo(result);
                        }
                        else {
                            HideAddPOITip(e);
                            ShowMsgBox("El sistema no pudo ubicar la ciudad del punto seleccionado, por favor intentelo denuevo.");
                            return;
                        }

                    });
                }
                else {
                    HideAddPOITip(e);
                    ShowMsgBox("El sistema no pudo ubicar la ciudad del punto seleccionado, por favor intentelo denuevo.");
                    return;
                }

            },
            function (error) {
                if (error != null)
                    ShowMsgBox(error.ErrorMessage);
            }
        );        
        
    }

}

// Populate Groups, Categories,  Subcategories and Services

function GetGroups() {
    dojo.byId('btnAddPOINext').style.display = "none";
    PageMethods.GetGroups(ProcessGetGroups);
}

function ProcessGetGroups(result) {
    var d = dojo.byId('addPOIGroup');
    d.innerHTML = "";
    if (result != null) {
        var f;
        var h = "";
        for (k = 0; k < result.length; k++) {
            if (k == 0) f = result[k].Id;
            h += "<option value='" + result[k].Id + "'>" + result[k].Description + "</option>";
        }
        
        if ($.browser.msie)
            $(h).appendTo("#addPOIGroup");
        else
            d.innerHTML = h;

        if (_beingLoadedToModify == true) {
            dojo.byId('addPOIGroup').value = _poi.GroupId;
            GetCategoriesByGroupId(_poi.GroupId);
        }
        else
            GetCategoriesByGroupId(f);
    }
    else {
        dojo.byId("addPOICategory").innerHTML = "";
        dojo.byId("addPOISubcategory").innerHTML = "";
        dojo.byId('addPOIServicesContainer').innerHTML = "";
    }

    dojo.byId('btnAddPOINext').style.display = "block";
}

function GetCategoriesByGroupId(id) {
    dojo.byId('btnAddPOINext').style.display = "none";
    PageMethods.GetCategoriesByGroupId(id, ProcessGetCategoriesByGroupId);
}

function ProcessGetCategoriesByGroupId(result) {
    var d = dojo.byId('addPOICategory');
    d.innerHTML = "";
    if (result != "") {
        var f;
        var h = "";
        for (k = 0; k < result.length; k++) {
            if (k == 0) f = result[k].Id;
            h += "<option value='" + result[k].Id + "'>" + result[k].Description + "</option>";
        }

        if ($.browser.msie)
            $(h).appendTo("#addPOICategory");
        else
            d.innerHTML = h;
        if (_beingLoadedToModify == true) {
            dojo.byId('addPOICategory').value = _poi.CategoryId;
            GetSubCategoriesByCategoryId(_poi.CategoryId);        
        }
        else
            GetSubCategoriesByCategoryId(f);
    }
    else {
        dojo.byId('addPOISubcategory').innerHTML = "";
        dojo.byId('addPOIServicesContainer').innerHTML = "";
    }
    dojo.byId('btnAddPOINext').style.display = "block";
}

function GetSubCategoriesByCategoryId(id) {
    dojo.byId('btnAddPOINext').style.display = "none";
    PageMethods.GetSubCategoriesByCategoryId(id, ProcessGetSubCategoriesByCategoryId);
}

function ProcessGetSubCategoriesByCategoryId(result) {
    var d = dojo.byId('addPOISubcategory');
    d.innerHTML = "";
    if (result != "") {
        var h = "";
        for (k = 0; k < result.length; k++) {
            h += "<option value='" + result[k].Id + "'>" + result[k].Description + "</option>";
        }

        if ($.browser.msie)
            $(h).appendTo("#addPOISubcategory");
        else
            d.innerHTML = h;

        if (_beingLoadedToModify == true)
            dojo.byId('addPOISubcategory').value = _poi.SubCategoryId;

        GetServicesByCategoryId($("#addPOIGroup").val());

    }
    else {
        dojo.byId('addPOIServicesContainer').innerHTML = "";
    }

    dojo.byId('btnAddPOINext').style.display = "block";
}

var _services = [];

function AddRemoveService(id, o) {

    if (o.checked == true)
        _services.push(id);
    else {
        for (i = 0; i < _services.length; i++) {
            if (_services[i] == id) {
                _services.splice(i, 1);
                break;
            }
        }
    }

}

function GetServicesByCategoryId(id) {
    dojo.byId('btnAddPOINext').style.display = "none";
    PageMethods.GetServicesByCategoryId(id, ProcessGetServicesByCategoryId);
}

function ProcessGetServicesByCategoryId(result) {
    var d = dojo.byId('addPOIServicesContainer');
    _services = [];
    if (result != "") {
        var h = "";      
        h += "<table cellpadding=\"1\" cellspacing=\"0\" border=\"0\" width=\"95%\">";
        for (k = 0; k < result.length; k++) {
            if (_beingLoadedToModify == true) {

                var a = false;
                if(_poi.Services!=null)
                    for (j = 0; j < _poi.Services.length; j++) {
                        if (result[k].Id == _poi.Services[j])
                        {
                            h += "<tr><td width=\"20\"><input type='checkbox' value='" + result[k].Id + "' checked='true' onclick='AddRemoveService(" + result[k].Id + ",this);' /></td><td>" + result[k].Description + "</td></tr>";
                            _services.push(_poi.Services[j])
                            a = true;
                            break;
                        }
                    }
                
                if(a==false)
                    h += "<tr><td width=\"20\"><input type='checkbox' value='" + result[k].Id + "' onclick='AddRemoveService(" + result[k].Id + ",this);' /></td><td>" + result[k].Description + "</td></tr>";

            }
            else
                h += "<tr><td width=\"20\"><input type='checkbox' value='" + result[k].Id + "' onclick='AddRemoveService(" + result[k].Id + ",this);' /></td><td>" + result[k].Description + "</td></tr>";
        }
        h += "</table>";        
        d.innerHTML = h;
    }
    else
        d.innerHTML = "";


    _beingLoadedToModify = false;
}

// Add / Update POI

function AddPOI() {


    var p = new esri.geometry.Point(dojo.byId('poiLong').value, dojo.byId('poiLat').value, _map.spatialReference);
    p = _currentMapType == "BING" ? esri.geometry.webMercatorToGeographic(p) : p;

    var lat = p.y;
    var long = p.x;

    // Step 1

    var name = dojo.byId('txtAddPOIName').value;
    var ruc = dojo.byId('txtAddPOIRUC').value;
    var contact = dojo.byId('txtAddPOIContact').value;
    var phone1 = dojo.byId('txtAddPOIPhone2').value;
    var phone2 = "";
    var phone3 = dojo.byId('txtAddPOIPhone1').value;
    var web = dojo.byId('txtAddPOIWeb').value;
    var email = dojo.byId('txtAddPOIEmail').value;
    var sch = dojo.byId('txtAddPOISchedule').value;

    // Step 2
    var cityId = _cityId;
    var cityname = dojo.byId('addPOICityName').innerHTML.toString().trim();
    cityname = cityname!=""?cityname.substring(0,cityname.length-1):"";
    var address = dojo.byId('addPOIAddress').innerHTML;
    var num = dojo.byId('txtAddPOINumber').value;
    var reference = dojo.byId('txtAddPOIReference').value;
    var photo1 = dojo.byId('fileAddPOIPhoto1').value;
    var photo2 = dojo.byId('fileAddPOIPhoto2').value;
    var logo = dojo.byId('fileAddPOILogo').value;

    // Step 3

    var group = dojo.byId('addPOIGroup').value;
    var category = dojo.byId('addPOICategory').value;
    var subcategory = dojo.byId('addPOISubcategory').value;
    var services = _services;
    var otherservices = dojo.byId('txtAddPOIOtherService').value;

    // Step 4

    var publisherfnames = dojo.byId('txtAddPOIPublisherFirstName').value;
    var publisherlnames = dojo.byId('txtAddPOIPublisherLastName').value;
    var publisheremail = dojo.byId('txtAddPOIPublisherEmail').value;
    var puiblisherphone1 = dojo.byId('txtAddPOIPublisherPhone1').value;
    var puiblisherphone2 = dojo.byId('txtAddPOIPublisherPhone2').value;

    var owneremail = dojo.byId('userEmail').value;

    ShowLoading();

    if (!_gUniqueTrack.addpoi) {
        _gaq.push(['_trackEvent', 'Eventos Unicos', 'Finalizacion Publicacio de Puntos']);
        _gUniqueTrack.addpoi = true;
    }

    PageMethods.AddPOI(     owneremail, lat, long,
                            name, ruc, contact, phone1, phone2, phone3, web, email, sch,
                            cityId, cityname, address, num, reference, photo1, photo2, logo,
                            group, category, subcategory, services, otherservices,
                            publisherfnames, publisherlnames, publisheremail, puiblisherphone1, puiblisherphone2,
                            ProccessAddPOI
                        );

}

function UpdatePOI() {

    _poi.Latitude = dojo.byId('poiLat').value;
    _poi.Longitude = dojo.byId('poiLong').value

    // Step 1

    _poi.Name = dojo.byId('txtAddPOIName').value;
    _poi.Ruc = dojo.byId('txtAddPOIRUC').value;
    _poi.Contact = dojo.byId('txtAddPOIContact').value;
    _poi.Phone1 = dojo.byId('txtAddPOIPhone2').value;
    _poi.Phone2 = "";
    _poi.Phone3 = dojo.byId('txtAddPOIPhone1').value;
    _poi.Web = dojo.byId('txtAddPOIWeb').value;
    _poi.Email = dojo.byId('txtAddPOIEmail').value;
    _poi.Schedule = dojo.byId('txtAddPOISchedule').value;

    // Step 2
    _poi.CityId = _cityId;
    _poi.CityName = dojo.byId('addPOICityName').innerHTML.trim();
    _poi.CityName  =  _poi.CityName !=""? _poi.CityName.substring(0, _poi.CityName.length-1):"";
    _poi.Address = dojo.byId('addPOIAddress').innerHTML;
    _poi.Number = dojo.byId('txtAddPOINumber').value;
    _poi.Reference = dojo.byId('txtAddPOIReference').value;
    _poi.Photo1 = dojo.byId('fileAddPOIPhoto1').value;
    _poi.Photo2 = dojo.byId('fileAddPOIPhoto2').value;
    _poi.Logo = dojo.byId('fileAddPOILogo').value;

    // Step 3

    _poi.Group = dojo.byId('addPOIGroup').value;
    _poi.Category = dojo.byId('addPOICategory').value;

    var oldSubCategory = _poi.SubCategoryId;
    
    _poi.SubCategoryId = dojo.byId('addPOISubcategory').value;
    
    var oldServices = _poi.Services;
    _poi.Services = _services;

    _poi.OtherServices = dojo.byId('txtAddPOIOtherService').value;

    // Step 4

    _poi.PublisherFirstName = dojo.byId('txtAddPOIPublisherFirstName').value;
    _poi.PublisherLastname = dojo.byId('txtAddPOIPublisherLastName').value;
    _poi.PublisherEmail = dojo.byId('txtAddPOIPublisherEmail').value;
    _poi.PublisherPhone1 = dojo.byId('txtAddPOIPublisherPhone1').value;
    _poi.PublisherPhone2 = dojo.byId('txtAddPOIPublisherPhone2').value;

    _poi.OwnerEmail = dojo.byId('userEmail').value;

    ShowLoading();

    PageMethods.UpdatePOI(_poi, oldSubCategory, oldServices, ProccessUpdatePOI);   

}

function ProccessAddPOI(result) {
    HideLoading();
    if (result.HasError == false) {
        HideAddPOIWindow();
        
        var p = new esri.geometry.Point(dojo.byId('poiLong').value, dojo.byId('poiLat').value, _map.spatialReference);
        p = _currentMapType == "BING" ? esri.geometry.webMercatorToGeographic(p) : p;

        var lat = p.y;
        var long = p.x;

        DrawPointToEdit(result.ReturnValue, lat, long);
        ShowMsgBox('Gracias por subir tu punto comercial en Guíame,  el proceso de validación será en un máximo de 48 horas; durante este tiempo tu punto comercial no aparecerá en Guíame.');
        DeactivateAddPointOnMap();
    }
    else
        alert("Se produjo un error grave al intentar agregar el punto, por favor comuniquese con soporte@location-world.com");
}

function ProccessUpdatePOI(result) {
    HideLoading();
    if (result.HasError == false) {
        HideAddPOIWindow();
        ShowMsgBox('Las modificaciones a la información de su punto comercial han sido efectuadas con exito, recuerde que al modificar la información del punto este pasa a un estado de validación y por tanto no sera visible en Guíame.');
    }
    else
        alert("Se produjo un error grave al intentar editar el punto, por favor comuniquese con soporte@location-world.com");
}

function DrawPointOnMap(poiid, lat, long, owneremail) {
    var draw = false;
    if (_map.graphics != null) {
        if (GetGraphic(poiid) == null) {
            draw = true;
        }
    }
    else
        draw = true;

    var pointMap = new esri.geometry.Point(parseFloat(long), parseFloat(lat), _map.spatialReference);
    if (draw) {

        var icon = "images/marker.png";
        var userIcon = "images/user_poi.png";
        var i = icon;

        if (dojo.byId('userEmail').value != "")
            if (dojo.byId('userEmail').value == owneremail)
                i = userIcon;

        var myAttributes = { pID: poiid, pLong: long, pLat: lat, pOwnerEmail: owneremail };
        pointMap = GetConvertedPoint(pointMap);
        var g = new esri.Graphic(pointMap, new esri.symbol.PictureMarkerSymbol(i, 68, 68))
        .setAttributes(myAttributes);

        _map.graphics.add(g);

        if (_onNewPointClick == null && _onPOIMouseClick == null)
            _onNewPointClick = dojo.connect(_map.graphics, "onClick", ShowPOIInfoWindowFromMapPoint);
    }
    _map.centerAndZoom(pointMap, GetConvertedLevel(15));
}


// Draw Selected or Added POI at the map with basic info, id, lat and long

var _onNewPointClick = null;

function DrawAllMyPoints() {
    ShowLoading();
    PageMethods.GetPOIsByUser(dojo.byId('userEmail').value, ProccessGetPOIsByUserAndDrawOnMap);
}

function ProccessGetPOIsByUserAndDrawOnMap(result) {
    HideUserPOIListWindow();
    var draw = false;
    if (result.length > 0) {
        var pColl = new esri.geometry.Multipoint(_map.spatialReference);
        var symbolicon = "images/user_poi.png";
        for (k = 0; k < result.length; k++) {
            draw = false;
            if (_map.graphics != null) {
                if (GetGraphic(result[k].Id) == null) {
                    draw = true;
                }
            }
            else {
                draw = true;
            }

            if (draw) {
                var point = new esri.geometry.Point(parseFloat(result[k].Longitude), parseFloat(result[k].Latitude), _map.spatialReference);
                pColl.addPoint(point);
                var myAttributes = { pID: result[k].Id, pLong: result[k].Longitude, pLat: result[k].Latitude, pOwnerEmail: dojo.byId('userEmail').value };
                _map.graphics.add(new esri.Graphic(GetConvertedPoint(point), new esri.symbol.PictureMarkerSymbol(symbolicon, 68, 68)).setAttributes(myAttributes));
            }
        }

        if (_onNewPointClick == null && _onPOIMouseClick == null)
            _onNewPointClick = dojo.connect(_map.graphics, "onClick", ShowPOIInfoWindowFromMapPoint);

        _EVCZpointsColl = new Deprivation(pColl);
        //..........................................................//
        setTimeout("SetLevelAllFunctions();", 500);
    }
    else {
        ShowMsgBox('Aún no posees puntos en tu lista.');
    }

    HideLoading();
}

function DrawPointToEdit(poiid, lat, long) {
    var draw = false;
    if (_map.graphics != null) {
        if (GetGraphic(poiid) == null) {
            draw = true;
        }
    }
    else
        draw = true;

    var pointMap = new esri.geometry.Point(parseFloat(long), parseFloat(lat), _map.spatialReference);
    if (draw) {

        var userIcon = "images/user_poi.png";

        var myAttributes = { pID: poiid, pLong: long, pLat: lat, pOwnerEmail: dojo.byId('userEmail').value };        
        var p = GetConvertedPoint(pointMap);
        var g = new esri.Graphic(p, new esri.symbol.PictureMarkerSymbol(userIcon, 68, 68))
        .setAttributes(myAttributes);

        _map.graphics.add(g);

        if (_onNewPointClick == null && _onPOIMouseClick == null)
            _onNewPointClick = dojo.connect(_map.graphics, "onClick", ShowPOIInfoWindowFromMapPoint);
    }
    _map.centerAndZoom(GetConvertedPoint(pointMap), GetConvertedLevel(15));
}

// Populate User POI List

function GetPOIsByUser() {
    ShowLoading();
    PageMethods.GetPOIsByUser(dojo.byId('userEmail').value, ProccessGetPOIsByUser);
}

function ProccessGetPOIsByUser(result) {

    if (result.length > 0) {

        var list = "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"790\">";

        for (i = 0; i < result.length; i++) {
            var s = result[i].AuthorizationStatus;
            var c = "poilist_item";
            if (i % 2 == 0)
                c = "poilist_alternate_item";

            var btnEdit = "<div style=\"margin:0px auto; width:80px; float:right;\"><a href=\"javascript:void(0);\" onclick=\"btnPOIListEdit_click(" + result[i].Id + ","+ result[i].Latitude + "," + result[i].Longitude + ");\" class=\"btnStep\">EDITAR</a></div>";
            var btnDelete = "<div style=\"margin:0px auto; width:80px; float:right;\"><a href=\"javascript:void(0);\" onclick=\"btnPOIListDelete_click(" + result[i].Id + ");\" class=\"btnStep\">ELIMINAR</a></div>";

            switch (s) {
                case 0:
                    ss = "En revisión (Nuevo)";
                    break;
                case 1:
                    ss = "Publicado";
                    break;
                case 2:
                    ss = "En revisión (Información Modificada)";
                    break;
                case 3:
                    ss = "En revisión (Ubicación Modificada)";
                    break;
                case 15:
                    ss = "Rechazado<br />Motivo: " + result[i].Observations;
                    break;
                default:
                    ss = "";
            }

            list += "<tr class=\"" + c + "\"><td width=\"30\">" + (i + 1) + ".-</td><td width=\"380\">" + result[i].Name + "</td><td width=\"170\">" + ss + "</td><td width=\"80\">" + btnEdit + "</td><td width=\"80\">" + btnDelete + "</td></tr>";
        }

        list += "</table>";

        dojo.byId('editPOIList').innerHTML = list;

        ShowUserPOIListWindow();
    }
    else
        ShowWelcomeScreenWindow();
    HideLoading();
}

// Delete POI

function DeletePOI(id) {
    PageMethods.DeletePOI(id, ProccessDeletePOI);
    ShowLoading();
}

function ProccessDeletePOI(result) {
    HideLoading();
    if (result.HasError == false) {
        HideDeletePOIWindow();        
        var g = GetGraphic(result.ReturnValue);        
        if (g)
            _map.graphics.remove(g);
        
        ShowSuccessDeletePOIWindow();

        if (dojo.byId('searchPanel').style.display != "block")
            ShowMainPanel();

    }
    else {
        //ShowMsgBox('Se produjo un ERROR grave al intentar ejecutar la operación requerida, por favor contáctese a soporte@location-world.com');
        ShowMsgBox(result.ErrorMessage);
        //alert(result.ReturnValue);
    }
}

// Change Symbol when login in case of a user POI being displayed
function CheckCurrentGraphics() {
    var userIcon = "images/user_poi.png";
    if (_map.graphics != null) {
        var graphics = _map.graphics.graphics;
        for (var z = 0; z < graphics.length; z++) {
            if (graphics[z].attributes != undefined) {
                if (dojo.byId('userEmail').value != "")
                    if (dojo.byId('userEmail').value == graphics[z].attributes.pOwnerEmail)
                        graphics[z].setSymbol(new esri.symbol.PictureMarkerSymbol(userIcon, 68, 68));
            }
        }
    }
}

// Load POI info into edit window

function LoadPOIInfo() {      

    CleanAddPOIForm();

    dojo.byId('poiLat').value = _poi.Latitude;
    dojo.byId('poiLong').value = _poi.Longitude;

    // Step 1

    dojo.byId('txtAddPOIName').value = _poi.Name;
    dojo.byId('txtAddPOIRUC').value = _poi.Ruc;
    dojo.byId('txtAddPOIContact').value = _poi.Contact;
    dojo.byId('txtAddPOIPhone1').value = _poi.Phone3.trim();
    dojo.byId('txtAddPOIPhone2').value = _poi.Phone1.trim();
    dojo.byId('txtAddPOIWeb').value = _poi.Web;
    dojo.byId('txtAddPOIEmail').value = _poi.Email;
    dojo.byId('txtAddPOISchedule').value = _poi.Schedule;

    // Step 2
    
    dojo.byId('txtAddPOINumber').value = _poi.Number;
    dojo.byId('txtAddPOIReference').value = _poi.Reference;
    
    dojo.byId('fileAddPOIPhoto1').value = _poi.Photo1;
    dojo.byId('fileAddPOIPhoto2').value = _poi.Photo2;
    dojo.byId('fileAddPOILogo').value = _poi.Logo;

    // Step 3
    // This Values must be loaded upon drop down list load.
    dojo.byId('txtAddPOIOtherService').value = _poi.OtherServices;

    // Step 4

    dojo.byId('txtAddPOIPublisherFirstName').value = _poi.PublisherFirstName;
    dojo.byId('txtAddPOIPublisherLastName').value = _poi.PublisherLastname;
    dojo.byId('txtAddPOIPublisherEmail').value = _poi.PublisherEmail;
    dojo.byId('txtAddPOIPublisherPhone1').value = _poi.PublisherPhone1.trim();
    dojo.byId('txtAddPOIPublisherPhone2').value = _poi.PublisherPhone2.trim();
    
    ShowAddPOIWindow();

    if (_addPOICurrentStep != 1) {
        HideAddPOIStep(_addPOICurrentStep);
        _addPOICurrentStep = 1;
        ShowAddPOIStep(_addPOICurrentStep);
    }

    dojo.byId('btnAddPOIPrevious').style.display = "none";
    dojo.byId('btnAddPOISave').style.display = "none";
    dojo.byId('btnAddPOINext').style.display = "block";

    dojo.byId('fileAddPOIPhoto1Container').innerHTML = "<iframe id=\"ifr\" marginheight=\"0\" marginwidth=\"0\" frameborder=\"0\" scrolling=\"none\" width=\"210\" height=\"45\" src=\"web_controls/upload.imgs.aspx?hdd=fileAddPOIPhoto1&u=" + _poi.Photo1 + "&path=" + dojo.byId('uploadPath').value + "\"></iframe>";
    dojo.byId('fileAddPOIPhoto2Container').innerHTML = "<iframe id=\"ifr\" marginheight=\"0\" marginwidth=\"0\" frameborder=\"0\" scrolling=\"none\" width=\"210\" height=\"45\" src=\"web_controls/upload.imgs.aspx?hdd=fileAddPOIPhoto2&u=" + _poi.Photo2 + "&path=" + dojo.byId('uploadPath').value + "\"></iframe>";
    dojo.byId('fileAddPOILogoContainer').innerHTML = "<iframe id=\"ifr\" marginheight=\"0\" marginwidth=\"0\" frameborder=\"0\" scrolling=\"none\" width=\"210\" height=\"45\" src=\"web_controls/upload.imgs.aspx?hdd=fileAddPOILogo&u=" + _poi.Logo + "&path=" + dojo.byId('uploadPath').value + "\"></iframe>";

    var objGeoprocessing = new lw.Geoprocessing();
    objGeoprocessing.ReverseGeocode(_poi.Longitude, _poi.Latitude, LoadCityAndStreetInfo, function (error) { if (error != null) alert(error.ErrorMessage); });

    GetGroups();

}

// Info Window Related

// This function calls when the user click at the result list link
function ShowPOIInfoWindowFromLink(id) {
    var graphic = GetGraphic(id);
    ShowLoading();
    PageMethods.GetPOI(id,
        function (result) {
            ShowPOIInfoWindow(result, graphic, 1);
        }
    );
    
}

// This function calls when the user click at the pushping
function ShowPOIInfoWindowFromMapPoint(event) {
    if (event.graphic.attributes)
        ShowLoading();
        PageMethods.GetPOI(event.graphic.attributes.pID,
            function OnSucceeded(result) {
                ShowPOIInfoWindow(result, event.graphic, 2);
            }
        );
}

function ShowPOIPicture(i) {
    if(dojo.byId('p1')!=null) dojo.byId('p1').style.display = "none";
    if (dojo.byId('p2') != null) dojo.byId('p2').style.display = "none";
    if (dojo.byId('p3') != null) dojo.byId('p3').style.display = "none";
    if (dojo.byId('p4') != null) dojo.byId('p4').style.display = "none";
    dojo.byId('p'+i).style.display = "inline";
}

function switchstars(s) {
    for (i = 0; i <= s; i++) {
        dojo.removeClass("star" + i , "staroff");
        dojo.addClass("star" + i, "staron");
    }
    
    for (i = s+1; i < 5; i++) {
        dojo.removeClass("star" + i, "staron");
        dojo.addClass("star" + i, "staroff");
    }

    var q = "";
    switch (s)
    {
        case 0:
            q = "Pésimo";
            break;

        case 1:
            q = "Malo";
            break;
        case 2:
            q = "Normal";
            break;
        case 3:
            q = "Muy Bueno";
            break;
        case 4:
            q = "Excelente";
            break;
    }
       
    dojo.byId('starTip').innerHTML = q;

}

function switchtooriginalscore(id) {
    dojo.byId('starTip').innerHTML = "";
    var e = window.event;
    //var tg = (window.event) ? e.srcElement : e.target;
    var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
    if (reltg.id.indexOf("star")==-1) {
        PageMethods.GetPOIScore(id,
        function (result) {

            for (i = 0; i < result; i++) {
                dojo.removeClass("star" + i, "staroff");
                dojo.addClass("star" + i, "staron");
            }

            for (i = result; i < 5; i++) {
                dojo.removeClass("star" + i, "staron");
                dojo.addClass("star" + i, "staroff");
            }



        }
    );
    }
}

function ScorePOI(id, score) {
    ShowLoading();
    PageMethods.ScorePOI(id, score + 1,
        function (result) {
            PageMethods.GetPOIScore(id,
                function (result) {

                    for (i = 0; i < result; i++) {
                        dojo.removeClass("star" + i, "staroff");
                        dojo.addClass("star" + i, "staron");
                    }

                    for (i = result; i < 5; i++) {
                        dojo.removeClass("star" + i, "staron");
                        dojo.addClass("star" + i, "staroff");
                    }

                    HideLoading();
                    _gaq.push(['_trackEvent', 'Eventos Recurrentes', 'Rate POI', 'id:' + id]);
                    ShowMsgBox('Tu calificación sobre este punto ha sido recibida, muchas gracias.');

                }
            );
        }
    );
}

function ShowPOIInfoWindow(result, graphic, src) {

    _poi = result;
    
    var lwPicturesPath = "http://www.guiame.com.ec/LWData/Pictures/";    
    var g2PicturesPath = hosturl + "/temp_uploads/";
    var imgHandler = hosturl +  "/handlers/thumbGen.ashx?i=";

    var encodedUrl = "http%3A%2F%2Fwww.guiame.com.ec%2Fguiame%2Fdefault.aspx%3Fp%3D" + _poi.Id + "%26lat%3D" + _poi.Latitude + "%26long%3D" + _poi.Longitude + "%26name%3D" + _poi.Name + "%26owner%3D" + _poi.OwnerEmail;
    var encodedTitle = _poi.Name;
    
    var p1 = ((result.Photo != "") ? "<div id=\"p1\"><img src=\"" + imgHandler + lwPicturesPath + result.Photo + "&h=100&w=130\" alt=\"\" /></div>" : "");
    var p2 = (result.Photo1 != "" ? "<div id=\"p2\" style=\"display:" + (p1 == "" ? "inline" : "none") + ";\"><img src=\"" + imgHandler + g2PicturesPath + result.Photo1 + "&h=100&w=130\" alt=\"\" /></div>" : "");
    var p3 = (result.Photo2 != "" ? "<div id=\"p3\" style=\"display:" + ((p1 == "" && p2 == "") ? "inline" : "none") + ";\"><img src=\"" + imgHandler + g2PicturesPath + result.Photo2 + "&h=100&w=130\" alt=\"\" /></div>" : "");
    var p4 = (result.Logo != "" ? "<div id=\"p4\" style=\"display:" + ((p1 == "" && p2 == "" && p3 == "") ? "inline" : "none") + ";\"><img src=\"" + imgHandler + g2PicturesPath + result.Logo + "&h=120&w=130\" alt=\"\" /></div>" : "");

    var b1 = "<div onclick=\"ShowPOIPicture(1);\" style=\"float:left; cursor:pointer; margin:0px 1px; width:7px; height:7px; background-color: #555; display:" + (p1 == "" ? "none" : "block") + ";\"></div>";
    var b2 = "<div onclick=\"ShowPOIPicture(2);\" style=\"float:left; cursor:pointer; margin:0px 1px; width:7px; height:7px; background-color: #555; display:" + (p2 == "" ? "none" : "block") + ";\"></div>";
    var b3 = "<div onclick=\"ShowPOIPicture(3);\" style=\"float:left; cursor:pointer; margin:0px 1px; width:7px; height:7px; background-color: #555; display:" + (p3 == "" ? "none" : "block") + ";\"></div>";
    var b4 = "<div onclick=\"ShowPOIPicture(4);\" style=\"float:left; cursor:pointer; margin:0px 1px; width:7px; height:7px; background-color: #555; display:" + (p4 == "" ? "none" : "block") + ";\"></div>";

    var toolbox ="";
    if (dojo.byId('userEmail').value != "")
        if(result.OwnerEmail == dojo.byId('userEmail').value)
            toolbox = "<div style=\"padding:5px;\">" + dojo.byId('user_point_toolbox').innerHTML + "</div>";
    var stars = "";
    for (s = 0; s < _poi.Score; s++) {
        stars += "<div id=\"star" + s + "\" class=\"staron\" onmouseover=\"switchstars(" + s + ");\" onmouseout=\"switchtooriginalscore(" + _poi.Id + ");\" onclick=\"ScorePOI(" + _poi.Id + "," + s +");\"></div>";
    }

    if (_poi.Score < 5) {
        for (s = _poi.Score; s < 5; s++) {
            stars += "<div id=\"star" + s + "\" class=\"staroff\" onmouseover=\"switchstars(" + s + ");\" onmouseout=\"switchtooriginalscore(" + _poi.Id + ");\" onclick=\"ScorePOI(" + _poi.Id + "," + s + ");\"></div>";
        }
    }

    var html =
        "<div id=\"xx1\" style=\"overflow:scroll; height:100px; width:390px;\"><table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"380\" class=\"poi_info_text\">" +
            "<tr>" +
                "<td width=\"250\" valign=\"top\">" +
                    "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"245\">" +
                        "<tr style=\"display:" + (result.Address.trim() != "" ? "inline" : "none") + ";\">" +
                            "<td>" +
                                "<b>Dirección:</b> " + result.Address.trim() + "<br />" +
                            "</td>" +
                        "</tr>" +
                        "<tr style=\"display:" + (result.Reference.trim() != "" ? "inline" : "none") + ";\">" +
                            "<td>" +
                                "<b>Referencia:</b> " + result.Reference.trim() + "<br /><br />" +
                            "</td>" +
                        "</tr>" +
                        "<tr style=\"display:" + (result.Schedule.trim() != "" ? "inline" : "none") + ";\">" +
                            "<td>" +
                                "<b>Horario:</b><br />" + result.Schedule.trim() + "<br /><br />" +
                            "</td>" +
                        "</tr>" +
                        "<tr style=\"display:" + (result.Phone1.trim() != "" ? "inline" : "none") + ";\">" +
                            "<td>" +
                                "Tel: " + result.Phone1.trim() +
                            "</td>" +
                        "</tr>" +
                        "<tr style=\"display:" + (result.Phone3.trim() != "" ? "inline" : "none") + ";\">" +
                            "<td>" +
                                "Cel: " + result.Phone3.trim() +
                            "</td>" +
                        "</tr>" +
                        "<tr style=\"display:" + (result.Email.trim() != "" ? "inline" : "none") + ";\">" +
                            "<td>" +
                                "Mail: " + result.Email.trim() +
                            "</td>" +
                        "</tr>" +
                        "<tr style=\"display:" + (result.Web.trim() != "" ? "inline" : "none") + ";\">" +
                            "<td>" +
                                "Web: <a href=\"http://" + result.Web.trim() + "\" target=\"_blank\">" + result.Web.trim() + "</a>" +
                            "</td>" +
                        "</tr>" +
                        "<tr style=\"display:" + (result.Phone1.trim() != "" || result.Email.trim() != "" || result.Web.trim() != "" ? "inline" : "none") + ";\">" +
                            "<td style=\"height:10px;\">" +
                            "</td>" +
                        "</tr>" +
                        "<tr style=\"display:" + (result.GroupCategorySubcategoryNames.trim() != "" ? "inline" : "none") + ";\">" +
                            "<td>" +
                                "<b>Categorias</b>: " + result.GroupCategorySubcategoryNames.trim() +
                            "</td>" +
                        "</tr>" +
                        "<tr style=\"display:" + (result.ServicesNames.trim() != "" ? "inline" : "none") + ";\">" +
                            "<td>" +
                                "<b>Servicios</b>: " + result.ServicesNames.trim() +
                            "</td>" +
                        "</tr>" +
                        "<tr style=\"display:" + (result.OtherServices.trim() != "" ? "inline" : "none") + ";\">" +
                            "<td>" +
                                "<b>Otros Servicios</b>: " + result.OtherServices.trim() +
                            "</td>" +
                        "</tr>" +
                    "</table>" +
                    "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" style=\"margin-top:5px;\">" +
                        "<tr>" +
                            "<td width=\"85\">" +
                                "<a href=\"javascript:void(0);\" onclick=\"ShowSendSMSWindow();\">Enviar via SMS</a>" +
                            "</td>" +
                            "<td width=\"80\">" +
                                "Compartir en:" +
                            "</td>" +
                            "<td width=\"20\">" +
                                "<a href=\"javascript:void(0);\" onclick=\"TryToSharePointAtFacebook('" + encodedUrl + "&t=" + encodedTitle + "');\"><img src=\"images/facebook_icon.png\" /></a>" +
                            "</td>" +
                            "<td width=\"20\">" +
                                "<a href=\"http://twitter.com/share?url=" + encodedUrl + "&text=Compratir+en+twitter\" target=\"blank\"><img src=\"images/twitter_icon.png\" /></a>" +
                            "</td>" +
                            "<td width=\"20\">" +
                                "<a href=\"javascript:void(0);\" onclick=\"ShowSendPOIByEmailWindow();\" ><img src=\"images/email_icon.png\" /></a>" +
                            "</td>" +
                            "<td width=\"20\">" +
                                "<a href=\"javascript:void(0);\" onclick=\"PrintPOI(" + _poi.Id + ");\" ><img src=\"images/print_poi.png\" /></a>" +
                            "</td>" +
                        "</tr>" +
                    "</table>" +
                    "<div style=\"height:7px;\"></div>" +
                    "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">" +
                        "<tr>" +
                            "<td>Califica este punto: </td>" +
                            "<td>" +
                                stars + "&nbsp;&nbsp;<div id=\"starTip\" style=\"display:inline; color:#00344E;\"></div>" +
                            "</td>" +
                        "</tr>" +
                    "</table>" +
                    "<div style=\"height:7px;\"></div>" +                    
                    "<a style=\"padding-left:5px; text-decoration:none;\" href=\"javascript:void(0);\" onclick=\"CenterHere(" + _poi.Id + ");\">Centrar mapa en este punto</a>" + " " + "<a style=\"padding-left:5px; text-decoration:none;\" href=\"javascript:void(0);\" onclick=\"PoiFeedback();\">Reportar Error</a>" +
                    "<div style=\"height:3px;\"></div>" +
                    "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">" +
                        "<tr>" +
                            "<td style=\"padding-left:5px;\">" +
                                "<a href=\"javascript:void(0);\" style=\"text-decoration:none;\" onclick=\"$('#nearToSearch').toggle();\">Buscar cerca de este punto:</a>" +
                            "</td>" +
                        "</tr>" +
                        "<tr id=\"nearToSearch\" style=\"display:block;\">" +
                            "<td style=\"padding-left:3px;\">" +
                                "<input style=\"border: 1px solid #ccc;\" id=\"txtNearToCriteria\" type=\"text\" /> " +
                                "<a href=\"javascript:void(0);\" onclick=\"SearchPOIsNearToFirstPage('" + _poi.Longitude + "," + _poi.Latitude + "'," + _poi.Id + ");\">Buscar</a>" +
                            "</td>" +
                        "</tr>" +
                    "</table>" +
                    toolbox +                    
                "</td>" +
                "<td width=\"130\" valign=\"top\" align=\"center\">" +
                    "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"130\" >" +
                        "<tr>" +
                            "<td>" +
                                b1 + b2 + b3 + b4 +
                            "</td>" +
                        "</tr>" +
                        "<tr>" +
                            "<td style=\"height:1px;\">" +                                
                            "</td>" +
                        "</tr>" +
                        "<tr>" +
                            "<td style=\"background-color:#fff;\" align=\"center\">" +
                                p1 + p2 + p3 + p4 +
                            "</td>" +
                        "</tr>" +
                    "</table>" +                    
                "</td>" +
            "</tr>" +
        "</table></div>";
    //
    //"<a href=\"javascript:void(0);\" onclick=\"TryToSharePointAtFacebook('" + encodedUrl + "%26t=" + encodedTitle + "');\"><img src=\"images/facebook_icon.png\" /></a>" +
    _map.infoWindow.setTitle(result.Name)
    .setContent(html);
    
	_map.infoWindow.show(_map.toScreen(graphic.geometry), _map.getInfoWindowAnchor(_map.toScreen(graphic.geometry)));
	
    var pp = document.getElementById('xx1').scrollHeight;
	_map.infoWindow.hide();

	document.getElementById('xx1').style.height = (pp+5) + 'px';
	document.getElementById('xx1').style.overflow = 'hidden';
    
    _map.infoWindow.resize(380, pp+45);
	_map.infoWindow.show(_map.toScreen(graphic.geometry), _map.getInfoWindowAnchor(_map.toScreen(graphic.geometry)));
    
    if (src == 1) {
        var point = new esri.geometry.Point(parseFloat(graphic.attributes.pLong), parseFloat(graphic.attributes.pLat), _map.spatialReference);
        //if (!IsInsideExtent(point, _map.extent)) {
        if (!IsInsideExtent(graphic.geometry, _map.extent)) {
            //_map.centerAndZoom(point, BASE_POINT_LEVEL);
            _map.centerAndZoom(graphic.geometry, GetConvertedLevel(BASE_POINT_LEVEL)); 
        }
    }
    HideLoading();
}

function AddressFeedback(lat, lon) {
    var email = dojo.byId("userEmail").value;
    var name = $("#facebookProfileName").val().trim();
    if (email == "")
        email = $("#facebookProfileEmail").val().trim()
    window.open(_furl + "?url=http://www.guiame.com.ec&lat=" + lat + "&lon=" + lon.toString() + (email == "" ? "" : "&email=" + email) + (name == "" ? "" : "&name=" + name), "LWFeedback", "", false);
}

function PoiFeedback() {
    var email = dojo.byId("userEmail").value;
    var name = $("#facebookProfileName").val().trim();
    if (email == "")
        email = $("#facebookProfileEmail").val().trim()
    window.open(_furl + "?url=http://www.guiame.com.ec&lat=" + _poi.Latitude + "&lon=" + _poi.Longitude + "&extra=" + _poi.Name + ", " + _poi.CityName + ", " + _poi.Address + (email == "" ? "" : "&email=" + email) + (name == "" ? "" : "&name=" + name), "LWFeedback", "", false);
}

function CenterHere(id) {
    _map.infoWindow.hide();
    _map.centerAndZoom(GetGraphic(id).geometry, GetConvertedLevel(15));
}

function PrintPOI(id) {
    _gaq.push(['_trackEvent', 'Eventos Recurrentes', 'Imprimir Punto', 'id: ' + id]);
    window.open("PrintPOI.aspx?id=" + id, "", "height=300, width=400");

}


// POI Movement Related

var _onNewPointMouseDown = null;
var _onNewPointMouseUp = null;
var _onNewPointMouseDrag = null;

function ActivatePOIMovement() {
    DeactivateAddPointOnMap();

    dojo.disconnect(_onNewPointClick);

    _map.infoWindow.hide();

    _onNewPointMouseDown = dojo.connect(_map.graphics, "onMouseDown", OnNewPointMouseDown);
    _onNewPointMouseDrag = dojo.connect(_map.graphics, "onMouseDrag", OnNewPointMouseDrag);    
    _onNewPointMouseUp = dojo.connect(_map.graphics, "onMouseUp", OnNewPointMouseUp);

}

function DeactivatePOIMovement() {
    
    dojo.disconnect(_onNewPointMouseDrag);
    dojo.disconnect(_onNewPointMouseUp);
    dojo.disconnect(_onNewPointMouseDown);

    dojo.disconnect(_onNewPointClick);
    if(_onPOIMouseClick==null)
        _onNewPointClick = dojo.connect(_map.graphics, "onClick", ShowPOIInfoWindowFromMapPoint);
}

var _currGraphic = null;
var currVertex = null;
var basePoint = null;
var currOffsetX = null;
var currOffsetY = null;

var _newPOILocation = null;
var _oldPOILocation = null;

function OnNewPointMouseDown(event) {
    _currGraphic = event.graphic;    
    if (_currGraphic.attributes.pOwnerEmail == dojo.byId('userEmail').value) {
        if (event.button != 2) {
            _map.infoWindow.hide();
            _map.disableMapNavigation();
            basePoint = event.mapPoint;            
            if (event.graphic.geometry.type == "point") {
                //_currGraphic.setSymbol(POINT_SYMBOL_OVER);
                currOffsetX = basePoint.x - _currGraphic.geometry.x;
                currOffsetY = basePoint.y - _currGraphic.geometry.y;
            }
        }
    }
    else return;
}

function OnNewPointMouseUp(event) {

    if (event.button != 2) {
        if (!_currGraphic) return;
        if (_currGraphic.attributes.pOwnerEmail == dojo.byId('userEmail').value) {
            _map.enableMapNavigation();
            
            var x;
            if (_currGraphic.geometry.type == "point") {
                var thisPoint = event.mapPoint;
                x = thisPoint;
                thisPoint.x = thisPoint.x - (currOffsetX);
                thisPoint.y = thisPoint.y - (currOffsetY);
                _currGraphic.setGeometry(thisPoint);
                //_currGraphic.setSymbol(POINT_SYMBOL);
                currOffsetX = 0;
                currOffsetY = 0;
            }
            _currGraphic = null;
            basePoint = null;

            if (x != null) {
                _newPOILocation = x;
                ShowMovementConfirmationWindow();
            }
        }
        else return;

    }

}

function OnNewPointMouseDrag(event) {
    if (!_currGraphic) return;
    if (_currGraphic.attributes.pOwnerEmail == dojo.byId('userEmail').value) {
        if (_currGraphic.geometry.type == "point") {
            var thisPoint = event.mapPoint;
            thisPoint.x = thisPoint.x - (currOffsetX);
            thisPoint.y = thisPoint.y - (currOffsetY);
            _currGraphic.setGeometry(thisPoint);
        }
        basePoint = event.mapPoint;
    }
    else return;

}

function UpdateNewPOILocation(id, p) {
    _map.centerAndZoom(p, GetConvertedLevel(15));
    var z = _currentMapType =="BING" ? esri.geometry.webMercatorToGeographic(p) : p;
    ReverseGeocodeNewPOILocation(id, z.y, z.x);
    _map.reposition();
}

function ReverseGeocodeNewPOILocation(id, latitude, longitude) {
    ShowLoading();
    var lat = latitude;
    var lon = longitude;
    new lw.Geoprocessing().ReverseGeocode(lon, lat, function (result) {


        if (result.City) {
            if (result.City.toUpperCase() != "NONE") {
                PageMethods.GetCityId(result.City, function (r) {
                    if (r != -1) {
                        _cityId = r;
                        var city = result.City;
                        var street1 = result.MainStreet.MainName || result.MainStreet.Alias || result.MainStreet.Nomenclature;
                        var street2 = result.Intersection.MainName || result.Intersection.Alias || result.Intersection.Nomenclature;
                        dojo.byId("poiLat").value = latitude;
                        dojo.byId("poiLong").value = longitude;
                        PageMethods.UpdatePOILocation(id, _cityId, city, street1, street2, dojo.byId('poiLat').value, dojo.byId('poiLong').value, ProccessUpdatePOILocation);
                    }
                    else {
                        HideLoading();
                        HideMovementConfirmationWindow();
                        DeactivatePOIMovement();
                        ShowMessageBox("El sistema no pudo ubicar la ciudad del punto seleccionado, por favor intentelo denuevo.");
                        RestoreOriginalLocation(_poi.Id, _poi.Latitude, _poi.Longitude);
                        return;
                    }

                });
            }
            else {
                HideLoading();
                HideMovementConfirmationWindow();
                DeactivatePOIMovement();
                ShowMessageBox("El sistema no pudo ubicar la ciudad del punto seleccionado, por favor intentelo denuevo.");
                RestoreOriginalLocation(_poi.Id, _poi.Latitude, _poi.Longitude);
                return;

            }
        }
        else {
            HideLoading();
            HideMovementConfirmationWindow();
            DeactivatePOIMovement();
            ShowMessageBox("El sistema no pudo ubicar la ciudad del punto seleccionado, por favor intentelo denuevo.");
            RestoreOriginalLocation(_poi.Id, _poi.Latitude, _poi.Longitude);
            return;

        }

    });
}

function ProccessUpdatePOILocation(result) {

    HideLoading();

    HideMovementConfirmationWindow();

    DeactivatePOIMovement();
    //ActivateAddPointOnMap();

    if (result.HasError == true)
        ShowMsgBox('Se produjo un ERROR grave al intentar ejecutar la operación requerida, por favor contáctese a soporte@location-world.com');
    else
        ShowMsgBox('La pocisión de tu punto comercial ha sido modificada, hasta validar la nueva ubicación este punto no podrá ser visualizado publicamente.');

}

function RestoreOriginalLocation(id, lat, long) {
    var g = null;
    g = GetGraphic(id);

    var pointMap = new esri.geometry.Point(parseFloat(long), parseFloat(lat), _map.spatialReference);
    pointMap = GetConvertedPoint(pointMap);
    g.setGeometry(pointMap);

    _map.centerAndZoom(pointMap, GetConvertedLevel(15));

}


// Send POI Info via SMS
function SendMobilMessage() {
    var mobil = document.forms[0]["txtSMSMobil"].value.trim();

    if (mobil.length == 0) {
        ShowMsgBox("Es necesario el número de celular para realizar la operación.");
        return false;
    }
    _gaq.push(['_trackEvent', 'Eventos Recurrentes', 'Envio POI por SMS']);
    PageMethods.SendPOIBySMS(_poi, mobil, SentSMSResponse);
    return false;
}

function SentSMSResponse(results) {
    if (results != null) {
        dojo.byId("divWindow").style["display"] = "none";
        dojo.byId("divTransparency2").style["display"] = "none";
        ShowMsgBox(results);
    }
}


// Send POI Info by Email

function SendPOIByEmail() {
    ShowLoading();
    _gaq.push(['_trackEvent', 'Eventos Recurrentes', 'Envio POI por EMAIL']);
    PageMethods.SendPOIByEmail(_poi, dojo.byId("txtSendPOIByEmailFrom").value, dojo.byId("txtSendPOIByEmailTo").value, ProcessSendPOIByEmail);
}

function ProcessSendPOIByEmail(result) {
    HideLoading();
    HideSendPOIByEmailWindow();   
    
    ShowMsgBox(result);
}

var _nearTo;

function SearchPOIsNearTo(latlong) {

    _map.infoWindow.hide();

    var callback = "criteria::" + _criteriaToTry +
                    "|nearTo::" + _nearToToTry +
					"|page::" + _actualPageToTry +
				    "|searchType::" + _searchTypeToTry;

    PageMethods.FreeSearchPOIsNearTo(callback, ProcessSearchPOIsNearToResponse);

    ShowLoading();
}

//Function that runs when the AddressSearch function was executed without any issue.
function ProcessSearchPOIsNearToResponse(results) {

    if (results != null) {
        var parameters = GetJSParameters(results);
        ShowFreeSearchResults(parameters);
    }
    else {        
        ShowMsgBox("No se encontraron Puntos de Interés bajo el criterio de búsqueda elegido cerca al punto seleccionado.");
        HideLoading();
    }

}

var _lastPoiLayerMouseClick = null;

function SearchPOIsNearToFirstPage(latlong, id) {

    if (id != -1) {        
        
        var g = GetGraphic(id);

        if (g) {
            g.symbol.url = "images/marker.png";

            var draw = true;
            for (i = 0; i < _lastPoiLayer.graphics.length; i++) {
                if (_lastPoiLayer.graphics[i].attributes.pID == id) {
                    draw = false;
                    break;
                }
            }

            if (draw) {
                _lastPoiLayer.add(g);
            }
            _lastPoiLayer.show();

            if (_lastPoiLayerMouseClick != null) {
                dojo.disconnect(_lastPoiLayerMouseClick);
            }
            _lastPoiLayerMouseClick = dojo.connect(_lastPoiLayer, "onClick", ShowPOIInfoWindowFromMapPoint);
        }
    }

    var c = dojo.byId('txtNearToCriteria').value;

    if (c.length == 0) {
        ShowMsgBox("Es necesario un criterio para realizar la búsqueda.");
        return false;
    }

    _actualPageToTry = 1;
    _criteriaToTry = dojo.byId('txtNearToCriteria').value;
    _searchTypeToTry = 6;
    _nearToToTry = latlong;

    SearchPOIsNearTo(latlong);
}

function SearchPOIsNearToAddressFirstPage(latlong) {
    var c = dojo.byId('txtWhat').value;

    if (c.length == 0) {
        ShowMsgBox("Es necesario un criterio para realizar la búsqueda.");
        return false;
    }

    _actualPageToTry = 1;
    _criteriaToTry = dojo.byId('txtWhat').value;
    _searchTypeToTry = 6;
    _nearToToTry = latlong;

    SearchPOIsNearTo(latlong);
}


