﻿var _currentExtent = { xmin: 0, xmax: 0, ymin: 0, ymax: 0 };

var _criteria;

var _criteriaToTry = "";
var _searchTypeToTry = 0;
var _actualPageToTry = 0;
var _nearToToTry = "";
var _currentExtentTotry = { xmin: 0, xmax: 0, ymin: 0, ymax: 0 }; ;

function NewFreeSearch() {

    _searchTypeToTry = 4;
    _actualPageToTry = 1;
    _criteriaToTry = "";
    _currentExtentTotry = { xmin: 0, xmax: 0, ymin: 0, ymax: 0 };

    FreeSearch();
}

//Function that makes a search of a specific criteria.
function FreeSearch() {

    _map.infoWindow.hide();

    var criteria = "";

    if (_searchTypeToTry == 4) {

        if (_criteriaToTry != "") {
            criteria = _criteriaToTry;
        }
        else {

            var pcriteria = "";
            var wcriteria = "";

            if (document.forms[0]["txtWhere"].value.trim() != "" && document.forms[0]["txtWhere"].value.indexOf("[Opcional") == -1) {
                wcriteria = document.forms[0]["txtWhere"].value.trim();
                wcriteria = wcriteria.replace(/[^a-zA-Z 0-9]+/g, '');
            }

            if (document.forms[0]["txtWhat"].value.trim() != "" && document.forms[0]["txtWhat"].value.indexOf("[Opcional") == -1) {
                pcriteria = document.forms[0]["txtWhat"].value.trim();
                pcriteria = pcriteria.replace(/[^a-zA-Z 0-9]+/g, '');
            }

            if (wcriteria != "" && pcriteria == "") {
                criteria = wcriteria;
            }
            else {
                if (wcriteria == "" && pcriteria != "") {
                    criteria = pcriteria;
                }
                else
                    criteria = wcriteria;
            }
        }
        
    }

    if (_searchTypeToTry == 6) {
        SearchPOIsNearTo(_nearTo);
        return;
    }

    if (_searchTypeToTry == 5 || _searchTypeToTry == 7) {
        criteria = _criteriaToTry;
        _currentExtentTotry = _currentExtent;
    }

    if (criteria.length == 0 || criteria == "") {
        ShowMsgBox("Es necesario un criterio para realizar la búsqueda.");
        return false;
    }

    var callback = "criteria::" + criteria +
                    "|xMin::" + _currentExtentTotry.xmin +
                    "|xMax::" + _currentExtentTotry.xmax +
                    "|yMin::" + _currentExtentTotry.ymin +
                    "|yMax::" + _currentExtentTotry.ymax +
					"|page::" + _actualPageToTry +
				    "|searchType::" + _searchTypeToTry;
    /*  +
    "|userEmail::" + dojo.byId('userEmail').value; */

    _gaq.push(['_trackEvent', 'Eventos Recurrentes', GetSearchTypeString(_searchTypeToTry), "Intentando buscar: " + criteria]);

    if (_criteriaToTry != "") {
        if (_searchTypeToTry == 4)
            PageMethods.FreeSearchPOIs(callback, ProcessFreeSearchResponse);
        else
            PageMethods.FreeSearchPOIsOnExtent(callback, ProcessFreeSearchResponse);
    }
    else {
        if (wcriteria != "" && pcriteria == "") {
            PageMethods.FreeSearchAddresses(callback, ProcessFreeSearchResponse);
        }
        else {
            if (wcriteria == "" && pcriteria != "") {
                if (_searchTypeToTry == 4)
                    PageMethods.FreeSearchPOIs(callback, ProcessFreeSearchResponse);
                else
                    PageMethods.FreeSearchPOIsOnExtent(callback, ProcessFreeSearchResponse);
            }
            else {
                PageMethods.FreeSearchAddresses(callback, ProcessComplexSearchResponse);
            }
        }
        /*
        if (dojo.byId("freeResultsOption").style.display == "none")
        PageMethods.FreeSearch(callback, ProcessFreeSearchResponse);
        else {
        if (dojo.hasClass("btnGoAddresses", "addresses_btn"))
        PageMethods.FreeSearchAddresses(callback, ProcessFreeSearchResponse);
        else {
        if (_searchType == 4)
        PageMethods.FreeSearchPOIs(callback, ProcessFreeSearchResponse);
        else
        PageMethods.FreeSearchPOIsOnExtent(callback, ProcessFreeSearchResponse);
        }
        }*/
    }
    ShowLoading();
}

function SearchByCategory(criteria, btnId) {

    $("div[id*=qsbtn]").each(function () {
        var id = $(this)[0].id;
        if (dojo.hasClass(id, id + "_over")) {
            dojo.removeClass(id, id + "_over");
            dojo.addClass(id, id);
        }
    });

    dojo.removeClass(btnId, btnId);
    dojo.addClass(btnId, btnId + "_over");

    _map.infoWindow.hide();

    _criteriaToTry = criteria;

    if (dojo.byId("quickSearchOptions").style.display != "block") {
        dojo.byId("quickSearchOptions").style.display = "block";
        $("#quickSearchOptions").position({
            of: $("#map"),
            my: "left top",
            at: "left top",
            collision: "none",
            offset: (70 + (230 - parseInt(document.getElementById("leftPanel").style.width))).toString() + " 0"
        });
        $("#quickSearchOptions").animate({ top: "+=35px" });
    }


}

function SearchByCategoryOnCurrentExtent() {
    
    btnCategories_click();

    _freeSearchHasBothResults = false;

    var extent = _currentMapType == "BING" ? esri.geometry.webMercatorToGeographic(_map.extent) : _map.extent;

    _currentExtentTotry.xmin = extent.xmin;
    _currentExtentTotry.xmax = extent.xmax;
    _currentExtentTotry.ymin = extent.ymin;
    _currentExtentTotry.ymax = extent.ymax;

    _searchTypeToTry = 5;
    _actualPageToTry = 1;

    var callback = "criteria::" + _criteriaToTry +
                    "|xMin::" + _currentExtentTotry.xmin +
                    "|xMax::" + _currentExtentTotry.xmax +
                    "|yMin::" + _currentExtentTotry.ymin +
                    "|yMax::" + _currentExtentTotry.ymax +
					"|page::" + _actualPageToTry +
				    "|searchType::" + _searchTypeToTry;

    PageMethods.FreeSearchPOIsOnExtent(callback, ProcessFreeSearchResponse);   

    ShowLoading();
}

function SearchByCategoryOnAnArea() {
    //_map.graphics.clear();   

    //_toolbar.activate(esri.toolbars.Draw.POLYGON);

    _freeSearchHasBothResults = false;

    btnCategories_click();
    _settingExtent = dojo.connect(_toolbar, "onDrawEnd", SetExtentAndDoSearchByCategory);
    _toolbar.activate(esri.toolbars.Draw.EXTENT);
}

function SetExtentAndDoSearchByCategory(extent) {

    //if (geometry.rings.length == 0) return;

    _toolbar.deactivate();
    dojo.disconnect(_settingExtent);

    extent = _currentMapType == "BING" ? esri.geometry.webMercatorToGeographic(extent) : extent;

    _currentExtentTotry.xmin = extent.xmin;
    _currentExtentTotry.xmax = extent.xmax;
    _currentExtentTotry.ymin = extent.ymin;
    _currentExtentTotry.ymax = extent.ymax;

    _searchTypeToTry = 7;
    _actualPageToTry = 1;

    var callback = "criteria::" + _criteriaToTry +
                    "|xMin::" + _currentExtentTotry.xmin +
                    "|xMax::" + _currentExtentTotry.xmax +
                    "|yMin::" + _currentExtentTotry.ymin +
                    "|yMax::" + _currentExtentTotry.ymax +
					"|page::" + _actualPageToTry +
				    "|searchType::" + _searchTypeToTry;

    PageMethods.FreeSearchPOIsOnExtent(callback, ProcessFreeSearchResponse);

    ShowLoading();

}

function GoFreeSearchAddresses() {
    
    _actualPageToTry = 1;

    dojo.removeClass("btnGoAddresses", "addresses_btn_b");
    dojo.addClass("btnGoAddresses", "addresses_btn");
    dojo.removeClass("btnGoPOIs", "pois_btn");
    dojo.addClass("btnGoPOIs", "pois_btn_b");

    FreeSearch();

}

function GoFreeSearchPOIs() {
    
    _actualPageToTry = 1;
    
    _addressLayer.clear();
    _addressLayer.hide();
    _map.infoWindow.hide();

    dojo.removeClass("btnGoPOIs", "pois_btn_b");
    dojo.addClass("btnGoPOIs", "pois_btn");
    dojo.removeClass("btnGoAddresses", "addresses_btn");
    dojo.addClass("btnGoAddresses", "addresses_btn_b");
    
    FreeSearch();

}

function ProcessComplexSearchResponse(results) {
    
    if (results != null) {
        var parameters = GetJSParameters(results);
        ShowAddressSuggestions(parameters);
    }
}

function ShowAddressSuggestions(parameters) {

    if (parameters.results.length == 0) {
        ShowMsgBox("No se encontraron Puntos de Interés en la dirección ingresada.");
        HideLoading();
        return false;
    }
       
    var items = GetLocationItems(parameters.results);

    var html = "";

    html += "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tr><td valign=\"top\" width=\"12\" style=\"padding-top:10px;\"><div class=\"addressSugestionsArrow\"></div></td><td width=\"338\" style=\"background-color:#fff; border:2px solid #00344E;\">";

    if(items.length==1)
        html += "<div style=\"padding:8px; text-align:center;\">Mostrando 1 resultado, para <b>" + dojo.byId('txtWhere').value + "</b></div>";
    else
        if (items.length < 5)
            html += "<div style=\"padding:8px; text-align:center;\">Mostrando " + items.length.toString() + " resultados, para <b>" + dojo.byId('txtWhere').value + "</b></div>";
        else
            html += "<div style=\"padding:8px; text-align:center;\">Mostrando los 5 primeros resultados, para <b>" + dojo.byId('txtWhere').value + "</b></div>";

    //Draw and Set the poi information over the map and the Results Panel.    
    for (var k = 0; k < (items.length > 5 ? 5 : items.length); k++) {
        html += CreateAddressResultListItemForPOISearchNearTo(items[k]);
    }
    html += "<div style=\"padding:8px; text-align:center;\">Si no encontraste la dirección que buscabas, por favor se más específico; te recomendamos utilizar el nombre de la ciudad y el nombre de la calle en tu búsqueda, ejemplo: naciones unidas, quito.</div>";
    html += "<div style=\"padding:8px; cursor:pointer; color:#00344E;\" onclick=\"CloseAddressSugestions();\"><b>Cancelar</b></div></td></tr></table>";
    
    dojo.byId("addressSuggestions").innerHTML = html;
    
    ShowTransparentPopupBackground();

    $("#addressSuggestions").animate({ width: "350px" }, { duration: 200, complete: function () {
        $("#addressSuggestions").animate({ height: "250px" }, { queue: false, duration: 600, easing: 'easeOutBounce' });
        $("#addressSuggestions").focus();
    }
    });
    
    HideLoading();

}

function CloseAddressSugestions() {
    $("#addressSuggestions").animate({ height: "0px" }, { duration: 200, complete: function () {
        dojo.byId("addressSuggestions").innerHTML = "";
        HideTransparentPopupBackground(); 
    } });    
}


//Function that runs when the AddressSearch function was executed without any issue.
function ProcessFreeSearchResponse(results) {

    if (results != null) {

        /*if(_criteria)
            if (_criteria != "")
                document.forms[0]["txtWhat"].value = "";*/

        if (results != "both" && results != "addresses" && results != "pois") {
            var parameters = GetJSParameters(results);
            ShowFreeSearchResults(parameters);
        }
        else {
            
            var criteria = document.forms[0]["txtWhat"].value.trim();
            criteria = criteria.replace(/[^a-zA-Z 0-9]+/g, '');

            var callback = "criteria::" + criteria +
                    "|xMin::" + _currentExtentTotry.xmin +
                    "|xMax::" + _currentExtentTotry.xmax +
                    "|yMin::" + _currentExtentTotry.ymin +
                    "|yMax::" + _currentExtentTotry.ymax +
					"|page::" + _actualPageToTry +
				    "|searchType::" + _searchTypeToTry;/*  +
                    "|userEmail::" + dojo.byId('userEmail').value; */

            if (results == "both") {
                _freeSearchHasBothResults = true;
                ShowMsgBox('Su búsqueda ha generado resultados en direcciones y puntos de interés.');
                PageMethods.FreeSearchAddresses(callback, ProcessFreeSearchResponse);                
            }
            else {
                _freeSearchHasBothResults = false;
                if (results == "addresses")
                    PageMethods.FreeSearchAddresses(callback, ProcessFreeSearchResponse);                
                else
                    PageMethods.FreeSearchPOIs(callback, ProcessFreeSearchResponse);
            }

            ShowLoading();

        }
    }
}

var _onPOIMouseClick = null;

function ProccessAddLogResponse(result) {
    //alert(result);
}

function ShowFreeSearchResults(parameters) {

    if (_criteria != parameters.criteria || _searchType != parameters.searchType) {
        if(parameters.nearTo)
            PageMethods.EntryLog(parameters.searchType, parameters.criteria + ":" + parameters.nearTo, parameters.totalResults, ProccessAddLogResponse);
        else
            PageMethods.EntryLog(parameters.searchType, parameters.criteria, parameters.totalResults, ProccessAddLogResponse);
    }

    if (parameters.results.length == 0) {
        ShowMsgBox("No se encontraron Puntos de Interés o Direcciones bajo el criterio de búsqueda elegido.");
        HideLoading();
        return false;
    }

    //Hera I set the current criteria and searchtype
    _criteria = parameters.criteria;
    _searchType = parameters.searchType;
    _actualPage = parameters.page;
    _currentExtent = { xmin: parameters.xMin, xmax: parameters.xMax, ymin: parameters.yMin, ymax: parameters.yMax };
    if (_searchType == 6)
        _nearTo = parameters.nearTo;
    else
        _nearTo = "";

    _gaq.push(['_trackEvent', 'Eventos Recurrentes', GetSearchTypeString(_searchType), _criteria + ", resultados: " + parameters.totalResults]);
    
    var userIcon = "images/user_poi.png";

    _map.graphics.clear();
   
    var items = GetLocationItems(parameters.results);

    var pColl = new esri.geometry.Multipoint(_map.spatialReference);
    var html = "";

    var bothResultsH = 0;
    if (_freeSearchHasBothResults)
        bothResultsH = 35;

    // Paging at top    
    var paging = CreatePaging(parameters);
    if (paging != "")
        _hasPagination = true;
    else
        _hasPagination = false;

    var paginationH = 0;
    if (_hasPagination)
        paginationH = 80;

    html += paging;

    var clientHeight = GetWinHeight();
    var newSearchButtonH = 45;

    html += "<div id=\"actualResult\" style=\"overflow-x:hidden; overflow-y:auto; height:" + (clientHeight - (165 + bothResultsH + paginationH + newSearchButtonH)) + "px;\">";
    
    //Draw and Set the poi information over the map and the Results Panel.    
    for (var k = 0; k < items.length; k++) {
        
        if (parameters.addressesResults == false.toString())
            html += CreatePOIResultListItem(items[k],k);
        else
            html += CreateAddressResultListItem(items[k]);

        if (parameters.addressesResults == false.toString()) {

            var symbolicon = "";
            if (dojo.byId('userEmail').value != "") {
                if (items[k].OwnerEmail == dojo.byId('userEmail').value)
                    symbolicon = userIcon;
            }

            if (symbolicon == "") {                
                symbolicon = "images/markers/" + (k + 1).toString() + ".png";
            }
            var point = new esri.geometry.Point(parseFloat(items[k].Longitude), parseFloat(items[k].Latitude), _map.spatialReference);
            pColl.addPoint(point);
            var myAttributes = { pID: items[k].ID, pLong: items[k].Longitude, pLat: items[k].Latitude, pOwnerEmail: items[k].OwnerEmail };
            _map.graphics.add(new esri.Graphic(GetConvertedPoint(point), new esri.symbol.PictureMarkerSymbol(symbolicon, 68, 68))
            .setAttributes(myAttributes));
        }
    }
    html += "</div>";
    
    if (_onPOIMouseClick == null)
        _onPOIMouseClick = dojo.connect(_map.graphics, "onClick", ShowPOIInfoWindowFromMapPoint);

    //Paging at bottom
    //html += CreatePaging(parameters);
    
    //Create New Search Button at bottom
    html += CreateBtnNewSeach();
    
    //Adjust Extent only if results are POIs
    if (parameters.addressesResults == false.toString()) {
        _EVCZpointsColl = new Deprivation(pColl);
        //..........................................................//
        setTimeout("SetLevelAllFunctions();", 500);
    }
    else
        _EVCZpointsColl = null;

    dojo.byId("searchResult").innerHTML = html;

    Cufon.replace('.btnNewSearch', { fontFamily: 'Movistar Text' });

    ShowResultPanel();
    
    HideLoading();    
    
    if (_freeSearchHasBothResults)
        $("#freeResultsOption").show();
    else
        $("#freeResultsOption").hide();

}

function GetSearchTypeString(searchType) {
    switch (searchType) {
        case 4:
            return "Busqueda Libre";
        case 5:
            return "Busqueda Rápida Mapa Actual";
        case 6:
            return "Busqueda Cerca de";
        case 7:
            return "Busqueda Rápida";
    }
}

function CreatePOIResultListItem(poi,i) {

    var html = "<div class=\"result_item\" onclick=\"return ShowPOIInfoWindowFromLink(" + poi.ID + ");\">";

    html += "<table cellpading=\"0\" cellspacing=\"0\" border=\"0\"><tr><td valign=\"top\">";
    html += "<div style=\"background: url(" + hosturl + "/images/markers/L" + (i + 1).toString() + ".png) no-repeat; width:24px; height:32px; \"></div>";

    html += "</td><td>";
    
    html += "<a style=\"font-family: Verdana; font-size:12px; color:#00344E; text-decoration:none;\" href=\"javascript:void(0);\" onclick=\"return ShowPOIInfoWindowFromLink(" + poi.ID + ");\"><b>" + poi.Name + "</b></a><br />";
    
    if (poi.CityName != "")
        html += "<span style=\"font-family: Verdana; color:#666;\">" + poi.CityName + "</span><br />";
    
    if (poi.Address != "")
        html += "<span style=\"font-family: Verdana; color:#000; font-size:11px;\">" + poi.Address + "</span><br />";

    html += "</td></tr></table></div>";

    return html;

}

var _onAddressPushpinClick = null;

function ShowAddressPushpingFromList(latitude, longitude) {
    var objGeoprocessing = new lw.Geoprocessing();
    objGeoprocessing.ReverseGeocode(longitude, latitude,
        function (result) {
            var html = "";            
            if (result.City) {
                if (result.City != "") {
                    html += result.MainStreet ? (result.MainStreet.MainName ? result.MainStreet.MainName + (result.Intersection ? (result.Intersection.MainName ? (" y " + result.Intersection.MainName) : "") : "") : "") : "";
                }
            }
            ShowAddressPushping(-1, html, latitude, longitude, result.City ? result.City : "");
        }, function () { });
}

function ShowAddressPushping(id, description, latitude, longitude, cityname) {    
    _addressLayer.clear();
    _map.infoWindow.hide();
    var pointMap = new esri.geometry.Point(parseFloat(longitude), parseFloat(latitude), _map.spatialReference);
    //var info = new esri.InfoTemplate("DIRECCIÓN:", description + "<br />" + cityname);
    var baseAttributes = { pID: -1, pLong: pointMap.x, pLat: pointMap.y, description: description, cityname: cityname };
    //.setInfoTemplate(info)
    var g = new esri.Graphic(GetConvertedPoint(pointMap), ADDRESS_PUSHPING_SYMBOL).setAttributes(baseAttributes);
    _addressLayer.add(g);
    _map.centerAndZoom(GetConvertedPoint(pointMap), GetConvertedLevel(15));
    _addressLayer.show();

    if (_onAddressPushpinClick == null)
        _onAddressPushpinClick = dojo.connect(_addressLayer, "onClick", ShowAddressInfoWindowFromMapPoint);
            
    //ShowAddressTip(g);
}

function ShowAddressInfoWindowFromMapPoint(event) {
    if (event.graphic.attributes)
        ShowAddressTip(event.graphic);    
}

function ShowAddressTip(graphic) {
    var html = "";

    html = "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">" +
                "<tr>" +
                    "<td>" +
                         graphic.attributes.description +
                    "</td>" +
                "</tr>" +
                "<tr>" +
                    "<td style=\"height:7px;\">" +
                    "</td>" +
                "</tr>" +
                "<tr>" +
                    "<td style=\"font-size:10px; padding-left:3px;\">" +
                        "Buscar cerca de aquí:" +
                    "</td>" +
                "</tr>" +
                "<tr>" +
                    "<td style=\"padding-left:3px; font-size:10px;\">" +
                        "<input style=\"border: 1px solid #ccc;\" id=\"txtNearToCriteria\" type=\"text\" /> " +
                        "<a href=\"javascript:void(0);\" onclick=\"SearchPOIsNearToFirstPage('" + graphic.attributes.pLong + "," + graphic.attributes.pLat + "',-1);\">Buscar</a>" +
                    "</td>" +
                "</tr>" +
                "<tr>" +
                    "<td style=\"height:7px;\">" +
                    "</td>" +
                "</tr>" +
                "<tr>" +
                    "<td style=\"font-size:10px;\">" +
                        "<a style=\"padding-left:5px; text-decoration:none;\" href=\"javascript:void(0);\" onclick=\"AddressFeedback(" + graphic.attributes.pLat + "," + graphic.attributes.pLong + ");\">Reportar Error</a>" +
                    "</td>" +
                "</tr>" +
            "</table>";

    _map.infoWindow.setTitle(graphic.attributes.cityname)
    .setContent(html);

    _map.infoWindow.resize(250, 120);
    _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 SearchPOINearAddress(lat, lon) {
    CloseAddressSugestions();
    SearchPOIsNearToAddressFirstPage(lon + ',' + lat);
}

function CreateAddressResultListItemForPOISearchNearTo(address) {
    var html = "<div class=\"result_item\" onclick=\"return SearchPOINearAddress(" + address.Latitude + "," + address.Longitude + ");\">";
    html += "<a style=\"font-family: Verdana; font-size:10px; color:#00344E; text-decoration:none;\" href=\"javascript:void(0);\" onclick=\"return SearchPOINearAddress(" + address.Latitude + "," + address.Longitude + ");\"><b>" + address.Description + "</b></a><br />";
    html += "<span style=\"font-family: Verdana; color:#666;\">" + address.CityName + "</span>";
    html += "</div>";

    return html;
}

function CreateAddressResultListItem(address) {
    var html = "<div class=\"result_item\" onclick=\"return ShowAddressPushpingFromList(" + address.Latitude + "," + address.Longitude + ");\">";
    html += "<a style=\"font-family: Verdana; font-size:12px; color:#00344E; text-decoration:none;\" href=\"javascript:void(0);\" onclick=\"return ShowAddressPushpingFromList(" + address.Latitude + "," + address.Longitude + ");\"><b>" + address.Description + "</b></a><br />";
    html += "<span style=\"font-family: Verdana; color:#666;\">" + address.CityName + "</span>";
    html += "</div>";

    return html;
}

function DoNewSearch() {
    _EVCZpointsColl = null;
    
    //Clear the map if exists objects on it.
    if (_map.graphics.graphics.length > 0) {
        _map.graphics.clear();
    }    

    _freeSearchHasBothResults = false;
    _hasPagination = false;
    _criteria = "";
    _currentExtent = { xmin: 0, xmax: 0, ymin: 0, ymax: 0 };
    _actualPage = 1;
    _searchType = 4;
    _addressLayer.clear();
    _addressLayer.hide();
    _lastPoiLayer.clear();
    _lastPoiLayer.hide();
    _map.infoWindow.hide();

    if (dojo.hasClass("btnGoAddresses", "addresses_btn_b")) {
        dojo.removeClass("btnGoAddresses", "addresses_btn_b");
        dojo.addClass("btnGoAddresses", "addresses_btn");
        dojo.removeClass("btnGoPOIs", "pois_btn");
        dojo.addClass("btnGoPOIs", "pois_btn_b");
    }

    ShowMainPanel();
    return false;
}


// Advanced Search Address

function SearchAddress() {
    var city = dojo.byId("txtAdvancedSearchCity").value;
    var street = dojo.byId("txtSearchAddressStreet").value;
    var intersection = dojo.byId("txtSearchAddressIntersection").value;
    if (city != "") {
        ShowLoading();
        var o = new lw.Geoprocessing();
        _gaq.push(['_trackEvent', 'Eventos Recurrentes', 'Busqueda Avanzada Direcciones', city + ':' + street + ':' + intersection ]);
        o.Geocode(city, street, intersection, ProcessSearchAddress, OnSearchAddressError);
    }
    else {
        ShowMsgBox("Debes especificar al menos la ciudad en la búsqueda.");
    }
}

function ProcessSearchAddress(result) {    
    if (result != null) {

        var street1 = "";
        var street2 = "";

        if (result.MainStreet)
            street1 = result.MainStreet.MainName || result.MainStreet.Alias || result.MainStreet.Nomenclature;

        if (result.Intersection)
            street2 = result.Intersection.MainName || result.Intersection.Alias || result.Intersection.Nomenclature;

        var address = "";

        if (street1 != "") {
            address = street1;
            if (street2 != "")
                address += " y " + street2;
        }
        else
            if (street2 != "")
                address = street2;

        ShowAddressPushping(-1, address, result.Coordinates.Latitude, result.Coordinates.Longitude, result.City);
    }
    HideLoading();
}

function OnSearchAddressError(error) {
    HideLoading();
    ShowMsgBox("No se encontro ninguna dirección con esos datos.");
}

// Advanced Search POI

function SearchPOI() {
    var city = dojo.byId("txtAdvancedSearchCity").value;
    var place = dojo.byId("txtSearchPOIName").value;

    if (city != "" && place!="") {
        var o = new lw.Geoprocessing();
        ShowLoading();
        _gaq.push(['_trackEvent', 'Eventos Recurrentes', 'Busqueda Avanzada Puntos de Interes', city + ':' + place]);
        o.GeoCodePlace(city, place, ProcessSearchPOI, OnSearchPOIError);
    }
    else {
        ShowMsgBox("Debes especificar la ciudad y el lugar que deseas buscar.");
    }

}

function ProcessSearchPOI(result) {
    if (result != null) {

        DrawPointOnMap(result.Id, result.Location.Coordinates.Latitude, result.Location.Coordinates.Longitude,result.Mail);

        //ShowAddressPushping(-1, address, result.Coordinates.Latitude, result.Coordinates.Longitude, result.City);
    }
    HideLoading();
}

function OnSearchPOIError(error) {    
    HideLoading();
    ShowMsgBox("No se encontro ningún lugar con esos datos.");
}

var _geo;

function UpdateGGPosition(position) {

    var objGeoprocessing = new lw.Geoprocessing();
    objGeoprocessing.ReverseGeocode(position.longitude, position.latitude,
        function (result) {
            var html = "";
            html += result.City ? result.City : "";
            if (html != "") {
                html += result.MainStreet ? (result.MainStreet.MainName ? ", " + result.MainStreet.MainName + (result.Intersection ? (result.Intersection.MainName ? (" y " + result.Intersection.MainName) : "") : "") : "") : "";
            }
            ShowAddressPushping(-1, html, position.latitude, position.longitude, "Mi ubicación actual aproximada:");
            HideLoading();
        }, function () { alert('Error'); HideLoading(); });
    
}

function GogleGearsHandleError(positionError) {
    ShowMsgBox('Google Gears no esta instaldo correctamente, para utilizar esta funcionalidad necesitas tener instalado Google Gears');
    HideLoading();
    //alert('Attempt to get location failed: ' + positionError.message);
}


