﻿var latilong;
var map;
var m_objMapCoordenates = new Array();
var markers = new Array();
var longitud = 0;
var latitud = 0;
//debugger
/*
LIBRERIA CLIENT FOR FRAMEWORK SOLUTIONS
AUTHOR: MCE, Silverio Del Orbe A.
Everest Datos S.A. (Empresa de Asosoria en Sistema de  Informacion Y Comercio Electronico)
*/
// --- Estandar Variables
var m_strLanguage_Code = "es";
var m_strSearchType = "neg";
var mv_intSearch_Num = -1;
//-----------Map Utils
var obj_Map_div = document.getElementById("map_canvas") ? document.getElementById("map_canvas") : null;
var obj_Map_Base = null;
var gdir;
/// Others declarations
var m_Search_Seccions = new Array('getGPSSearchData', 'getListingsData', 'sendFriend', 'SaveClickMap', 'SaveStatistics');
var g_objXmlHttp = null;
var initlat = 18.875103;
var initlong = -70.120239;
var isMozilla = false;
var isPostBack = true;
var level = "";
var canSearch = true; ///Cuando esta variable esta activa y se realiza el evento ZoomEnd entonces hace la función ajax y busca los resultados ordenados por distancia
var is_AutoZoomMap = true; ////Esta variable indica cuando se le puede hacer el zoom automatico al mapa
var letras = new Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
if (window.XMLHttpRequest)
    g_objXmlHttp = new XMLHttpRequest();
else
    g_objXmlHttp = new ActiveXObject("Microsoft.XMLHTTP");


//------------------------------------------------------------
// HASTA AQUI LIBRERIAS DE FUNCIONES DE MENU DEL  STM319.js...23/08/2005
//-------------------------------------->>>>>>>>>>>>>>>>>>>>>>
function initialize() {

    initializePoints(true, -1);
}

function initializeB2B() {

    if (document.getElementById("map")) {
        var mapa = document.getElementById("map");
        if (GBrowserIsCompatible() && mapa != null) {
            map = new GMap2(mapa);
            map.addControl(new GScaleControl());
            map.setUIToDefault();
            map.disableDoubleClickZoom();

            var longitud = parseFloat(document.getElementById("hdLon").value);
            var latitud = parseFloat(document.getElementById("hdLat").value);

            latlng = new GLatLng(latitud, longitud);
            var marcador = new GMarker(latlng);

            var codHTML = "<div class='mapText'>";
            codHTML += document.getElementById("hdDireccion").value + "<br />";
            codHTML += document.getElementById("hdTelefono").value;
            codHTML += "</div>";

            map.openInfoWindowHtml(latlng, codHTML);

            GEvent.addListener(marcador, "click", function() {

                map.openInfoWindowHtml(latlng, codHTML);
                map.setCenter(latlng, 16);

            });


            map.addOverlay(marcador);
            map.setCenter(latlng, 16);
        }
    }
}

function initializePoints(showText, p_map_id) {

    if (document.getElementById("map")) {
        var mapa = document.getElementById("map");
        if (GBrowserIsCompatible() && mapa != null) {

            if (showText) {
                map = new GMap2(document.getElementById("map"));
                map.addControl(new GScaleControl());
                map.setUIToDefault();
                map.disableDoubleClickZoom();
            }
            var cont = 0;
            var isFirstMarker = true;

            if (showText) {
                for (; cont < m_objMapCoordenates.length; cont++) {


                    var longitud = parseFloat(m_objMapCoordenates[cont][2]);
                    var latitud = parseFloat(m_objMapCoordenates[cont][3]);


                    if (longitud == 0 && latitud == 0)
                        continue;

                    latlng = new GLatLng(latitud, longitud);

                    map.addOverlay(crearMarcadorMapa(latlng, isFirstMarker, cont));

                    isFirstMarker = false;
                    //alert(longitud + ' ' + latitud + ' ' + parseFloat("4.55") + ' ' + document.getElementById("hdLat").value + ' ' + document.getElementById("hdLon").value);
                    //map.setCenter(new GLatLng(latitud, longitud), 15);


                    //  map.setCenter(latlng, 16);




                }
            }
            else if (p_map_id > 0) {
                var codHTML = "<div class='mapText'>";
                codHTML += m_objMapCoordenates[p_map_id][1] + ", " + m_objMapCoordenates[p_map_id][4] + "<br />";
                codHTML += m_objMapCoordenates[p_map_id][0];
                codHTML += "</div>";
                map.openInfoWindowHtml(markers[p_map_id].getPoint(), codHTML);
                map.setCenter(markers[p_map_id].getPoint(), 16);
            }
            //UPdateListing
            else {

                map = new GMap2(document.getElementById("map"));
                map.addControl(new GScaleControl());
                map.setUIToDefault();
                map.disableDoubleClickZoom();
                
                map.setUIToDefault();
                map.disableDoubleClickZoom();

                var longitud = parseFloat(document.getElementById("hdLon").value);
                var latitud = parseFloat(document.getElementById("hdLat").value);

                //alert(longitud + ' ' + latitud + ' ' + parseFloat("4.55") + ' ' + document.getElementById("hdLat").value + ' ' + document.getElementById("hdLon").value);
                //map.setCenter(new GLatLng(latitud, longitud), 15);

                latlng = new GLatLng(latitud, longitud);

                map.setCenter(latlng, 16);


                var marcador = new GMarker(latlng);
                map.addOverlay(marcador);
                GEvent.addListener(map, "dblclick", function(overlay, latlng) {
                    document.getElementById("hdLon").value = latlng.lng();
                    document.getElementById("hdLat").value = latlng.lat();
                    var marc = new GMarker(latlng);
                    map.addOverlay(marc);
                    getListingRefresh(latlng.lat(), latlng.lng());
                });
            }
            if (cont > 0) {

               AutoPositionAndZoom();
            }
        }
        //alert(document.getElementById("hdLon").value);
        // }
    }
}

function crearMarcadorMapa(point, isFirstMarker, p_id) {

    var marcador = new GMarker(point);
    marcador.value = p_id;
    //map.addOverlay(marcador);

    var codHTML = "<div class='mapText'>";
    codHTML += m_objMapCoordenates[p_id][1] + ", " +  m_objMapCoordenates[p_id][4] + "<br />";
    codHTML += m_objMapCoordenates[p_id][0];
    codHTML += "</div>";

    if (isFirstMarker == true) {
        map.openInfoWindowHtml(point, codHTML);
        map.setCenter(point, 16);
    }

    directionsPanel = document.getElementById("route");
    directions = new GDirections(map, directionsPanel);

    if (isFirstMarker == true) {
        GEvent.addListener(map, "dblclick", function(overlay, latlng) {
            getDirections(latlng.lat() + ', ' + latlng.lng());
            getAddress(latlng);

        });
    }


    markers[p_id] = marcador;


    GEvent.addListener(marcador, "click", function() {
        addMapInformation(p_id);
    });

    GEvent.addListener(directions, "error", function() {
        alert(msgErrorDir);

        var marker = new GMarker(point);
        var message = ["This", "is", "the", "secret", "message"];
        marker.value = number;
        GEvent.addListener(marker, "click", function() {
            var myHtml = "<b>#" + number + "</b><br/>" + message[number - 1];
            map.openInfoWindowHtml(point, myHtml);
        });
    });


    return marcador;

}

function addMapInformation(p_id) {
    var direccion = m_objMapCoordenates[p_id][1];
    var telefono = m_objMapCoordenates[p_id][0];

    var mapHTML = "<div class='mapText'>";
    mapHTML += direccion + ", " +  m_objMapCoordenates[p_id][4] + "<br />";
    mapHTML += telefono;
    mapHTML += "</div>";
    map.openInfoWindowHtml(markers[p_id].getPoint(), mapHTML);
}

function initializeMap() {

    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        map.setCenter(new GLatLng(18.37407000, -66.47371000), 8);
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        map.enableScrollWheelZoom();
        LoadBounds();
        //----
        GEvent.addListener(map, "dblclick", function(overlay, latlng) {
            is_AutoZoomMap = false;
            getListingRefresh(latlng.lat(), latlng.lng());
        });
        GEvent.addListener(map, "click", function(overlay, latlng) {
            if (latlng == null)
                return;
            is_AutoZoomMap = false;
            getListingRefresh(latlng.lat(), latlng.lng());
        });
        GEvent.addListener(map, "zoomend", function(p_oldLevel, p_newLevel) {
            is_AutoZoomMap = false;
            if (canSearch)
                getListingRefresh(map.getCenter().lat(), map.getCenter().lng());
            canSearch = true;
        });
    }

}



function getDirections(from) {

    //	track('DIRECTIONS_CLICK', listing_id, 'PROFILE_PAGE');

    var idioma = document.getElementById("hdIdioma").value;

    directionsPanel.innerHTML = '';
    directions.clear();
    directions.load("from: " + from + " to: " + latlng,
  	                    { "locale": idioma });

    trackCV(1, 22, 4);
}


function getAddress(latlng) {
    if (latlng != null) {
        var geocoder = new GClientGeocoder();
        geocoder.getLocations(latlng, showAddress);
    }
}



function showAddress(response) {
    if (!response || response.Status.code != 200) {
        alert("Status Code:" + response.Status.code);
    } else {
        var place = response.Placemark[0];

        document.getElementById("fromAddress").value = place.address;
    }
}


function LoadLocalData() {
    if (map != null) {
        //document.getElementById("__calle").value = "";
        removePoint();
        //LoadDataByName(p_field_name,p_field_value); // Default Coordenates 
        LoadBounds();
        //if (m_objMapCoordenates && m_objMapCoordenates.length>0)
        //obj_Map_Base.setCenter(new google.maps.LatLng(m_objMapCoordenates[0][1], m_objMapCoordenates[0][2]), 16);
    }
}



function removePoint() {
    try {
        map.clearOverlays();

    } catch (e) { alert(e.description) }

}


function LoadBounds() {
    if (m_objMapCoordenates == null || m_objMapCoordenates.length == 0) {
        return;
    }
    txt = "";
    var cont = 0;
    for (var i = m_objMapCoordenates.length - 1; i >= 0; i--) {
        try {

            var point = new GLatLng(m_objMapCoordenates[i][2], m_objMapCoordenates[i][1]);
            map.addOverlay(createMarker(point, i));
            cont++;
            //alert(m_objMapCoordenates[i][1] + " ," + m_objMapCoordenates[i][2]);
        } catch (e) { }




    }

    var isTopMap = document.getElementById("hdIsTopMap").value;
    if (isTopMap == "1" && is_AutoZoomMap)
        AutoPositionAndZoom();
    is_AutoZoomMap = true;

} // end function 


function createMarker(point, p_Num_id) {
    try {

        var marker;
        var isTopMap = document.getElementById("hdIsTopMap").value;

        //En caso de que sea el mapa grande
        if (isTopMap == "1") {


            var advert_type = m_objMapCoordenates[p_Num_id][4];
            var numberIcon = new GIcon();
            switch (advert_type) {
                case ('Bronce'):
                case ('Bronze'):
                    {
                        advert_type = 'Bronce';
                        numberIcon.iconSize = new GSize(44, 44);
                        numberIcon.shadowSize = new GSize(64, 44);
                        numberIcon.iconAnchor = new GPoint(22, 44);
                        numberIcon.infoWindowAnchor = new GPoint(22, 2);
                        break;
                    }

                case ('Plata'):
                case ('Silver'):
                    {
                        advert_type = 'Plata';
                        numberIcon.iconSize = new GSize(54, 54);
                        numberIcon.shadowSize = new GSize(74, 54);
                        numberIcon.iconAnchor = new GPoint(27, 54);
                        numberIcon.infoWindowAnchor = new GPoint(27, 2);
                        break;
                    }

                case ('Oro'):
                case ('Gold'):
                    {
                        advert_type = 'Oro';
                        numberIcon.iconSize = new GSize(64, 64);
                        numberIcon.shadowSize = new GSize(84, 64);
                        numberIcon.iconAnchor = new GPoint(32, 64);
                        numberIcon.infoWindowAnchor = new GPoint(32, 2);
                        break;
                    }

                case ('Normal'):
                    {
                        numberIcon.iconSize = new GSize(34, 34);
                        numberIcon.shadowSize = new GSize(54, 34);
                        numberIcon.iconAnchor = new GPoint(17, 34);
                        numberIcon.infoWindowAnchor = new GPoint(17, 2);
                    }
            }
            numberIcon.shadow = "http://www.google.com/mapfiles/shadow50.png"

            var lv_hdRootPath = document.getElementById("hdRootPath");
            var lv_str_rootPath = lv_hdRootPath == null ? "" : lv_hdRootPath.value;

            numberIcon.image = lv_str_rootPath + "Images/mapas/" + advert_type + "/" + (p_Num_id + 1) + ".gif";

            markerOptions = { "icon": numberIcon };
            markerOptions.title = (p_Num_id + 1) + ". " + m_objMapCoordenates[p_Num_id][0];

            marker = new GMarker(point, markerOptions);

            marker.value = p_Num_id;


            GEvent.addListener(marker, "click", function() {



                var codHTML = openFullMapHtmlWindow(p_Num_id);
                //  map.openInfoWindowHtml(point, codHTML.replace(/link_ad/g, "info_ad"));
                map.openInfoWindowHtml(point, codHTML);

            });
        }
        else {
            var marker = new GMarker(point);

            marker.value = p_Num_id;


            GEvent.addListener(marker, "click", function() {

                var nombre = m_objMapCoordenates[p_Num_id][0];

                var advert_id = m_objMapCoordenates[p_Num_id][3];
                var link = getRootPath() + "PAClientViewer.aspx?name=" + nombre + "&advert_id=" + advert_id; //m_objMapCoordenates[p_Num_id][4];

                var codHTML = "<div class='mapText'>";
                codHTML += nombre + "<br />";
                codHTML += "<a href='" + link + "'>Información Adicional</a>";
                codHTML += "</div>";
                map.openInfoWindowHtml(point, codHTML);
            });
        }




        markers[p_Num_id] = marker;
        return marker;
    } catch (e) {
        return null;
    }
}

function openFullMapHtmlWindow(p_Num_id) {
    var nombre = m_objMapCoordenates[p_Num_id][0];
    //var link = m_objMapCoordenates[p_Num_id][4];
    var advert_id = m_objMapCoordenates[p_Num_id][3];
    var listin_type = m_objMapCoordenates[p_Num_id][7];
    var link = getRootPath() + "PAClientViewer.aspx?name=" + nombre + "&advert_id=" + advert_id; //m_objMapCoordenates[p_Num_id][4];


    var divEmailNombre = "email_" + listin_type + advert_id;
    var divWebNombre = "web_" + listin_type + advert_id;
    var divAnuncioNombre = "anuncio_" + listin_type + advert_id;
    var divPdfNombre = "pdf_" + listin_type + advert_id;
    var divTexteaNombre = "textea_" + listin_type + advert_id;
    var divMenuNombre = "menu_" + listin_type + advert_id;
    var divVideoNombre = "video_" + listin_type + advert_id;

    var codHTML = "<div style='width: 250px'><div class='mapText'>";
    codHTML += nombre + " - <a href='#adv_" + (p_Num_id + 1) + "'>Ver en listado</a> <br />";
    codHTML += "<a href='" + link + "'>Información Adicional</a><div style='font-family: Arial; font-size: 9.5pt; text-align: left'>";
    //                        codHTML += document.getElementById(divEmailNombre) == null ? "" : document.getElementById(divEmailNombre).innerHTML;
    //                        codHTML += document.getElementById(divWebNombre) == null ? "" : document.getElementById(divWebNombre).innerHTML;
    //                        codHTML += document.getElementById(divAnuncioNombre) == null ? "" : document.getElementById(divAnuncioNombre).innerHTML;
    //                        codHTML += document.getElementById(divPdfNombre) == null ? "" : document.getElementById(divPdfNombre).innerHTML;
    //                        codHTML += document.getElementById(divTexteaNombre) == null ? "" : document.getElementById(divTexteaNombre).innerHTML;

    codHTML += document.getElementById(divEmailNombre) == null ? "" : "<div class='link_ad'>" + document.getElementById(divEmailNombre).innerHTML + "</div>";
    codHTML += document.getElementById(divWebNombre) == null ? "" : "<div class='link_ad'>" + document.getElementById(divWebNombre).innerHTML + "</div>";
    codHTML += document.getElementById(divAnuncioNombre) == null ? "" : "<div class='link_ad'>" + document.getElementById(divAnuncioNombre).innerHTML + "</div>";
    codHTML += document.getElementById(divPdfNombre) == null ? "" : "<div class='link_ad'>" + document.getElementById(divPdfNombre).innerHTML + "</div>";
    codHTML += document.getElementById(divTexteaNombre) == null ? "" : "<div class='link_ad'>" + document.getElementById(divTexteaNombre).innerHTML + "</div>";
    codHTML += document.getElementById(divMenuNombre) == null ? "" : "<div class='link_ad'>" + document.getElementById(divMenuNombre).innerHTML + "</div>";
    codHTML += document.getElementById(divVideoNombre) == null ? "" : "<div class='link_ad'>" + document.getElementById(divVideoNombre).innerHTML + "</div>";


    //                        codHTML += "<div>" +document.getElementsByName(divWebNombre)(0).outerHTML + "</div>";
    //                        codHTML += "<div>" +document.getElementsByName(divAnuncioNombre)(0).outerHTML + "</div>";
    //                        codHTML += "<div>" +document.getElementsByName(divPdfNombre)(0).outerHTML + "</div>";
    //                        codHTML += "<div>" +document.getElementsByName(divTexteaNombre)(0).outerHTML + "</div>";
    codHTML += "</div></div></div>";
    return codHTML;
}



function openHTMLWindow(point, p_Num_id) {

    var isTopMap = document.getElementById("hdIsTopMap").value;
    var codHTML
    //En caso de que sea el mapa grande
    if (isTopMap == "1") {
        var codHTML = openFullMapHtmlWindow(p_Num_id);
    }
    else {
        var nombre = m_objMapCoordenates[p_Num_id][0];
        var advert_id = m_objMapCoordenates[p_Num_id][3];
        var link = getRootPath() + "PAClientViewer.aspx?name=" + nombre + "&advert_id=" + advert_id; //m_objMapCoordenates[p_Num_id][4];

        codHTML = "<div class='mapText'>";
        codHTML += nombre + "<br />";
        codHTML += "<a href='" + link + "'>Información Adicional</a>";
        codHTML += "</div>";
    }
    map.openInfoWindowHtml(point, codHTML);

}

function openMarker(p_Num_id) {
    canSearch = false;
    map.setCenter(markers[p_Num_id - 1].getPoint(), 16);
    document.location = "#top";
    openHTMLWindow(markers[p_Num_id - 1].getPoint(), p_Num_id - 1);
}

function showMap() {
    var divMapa = document.getElementById('map');
    var estadoActual = divMapa.style.display;

    if (estadoActual == "none")
        divMapa.style.display = "block";
    else
        divMapa.style.display = "none";
}

function setValue(id, value) {
    document.getElementById(id).value = value;
}
/* PARA PRESENTAR DINAMICAMENTE LOS LISTINGS RELACIONADO A  LOS EVENTOS DEL MAPA
*  RECIBE: COORDENADAS
*  --------------------------------------------------
*/
function getListingRefresh(p_map_latitud, p_map_longitud) {
    longitud = p_map_longitud;
    latitud = p_map_latitud;
    var lv_str_Search_ID = document.getElementById("hdd_search_id_general");
    if (lv_str_Search_ID != null && lv_str_Search_ID.value != null) {
        PagesSincronizer(0, lv_str_Search_ID.value, p_map_latitud, p_map_longitud);
    }
}

/*
ready-State
0: The request is uninitialized (before you've called open()). 
1: The request is set up, but hasn't been sent (before you've called send()). 
2: The request was sent and is being processed (you can usually get content headers from the response at this point). 
3: The request is being processed; often some partial data is available from the response, but the server hasn't finished with its response. 
4: The response is complete; you can get the server's response and use it. 
Status-code
For example, you've certainly entered a request for a URL, typed the URL incorrectly, and received a 404 error code to indicate a page is missing. This is just 
one of many status codes that HTTP requests can receive as a status (see Resources for a link to the complete list of status codes). 403 and 401, both indicating 
secure or forbidden data being accessed, are also common. In each of these cases, these are codes that result from a completed response. In other words, the server 
fulfilled the request (meaning the HTTP ready state is 4), but is probably not returning the data expected by the client.
In addition to the ready state then, you also need to check the HTTP status. You're looking for a status code of 200 which simply means okay. With a ready state of 
4 and a status code of 200, you're ready to process the server's data and that data should be what you asked for (and not an error or other problematic piece 
of information). Add another status check to your callback method as shown in Listing 14.
*/
function updateAjaxComplete() {
    try {
        if (g_objXmlHttp.readyState == 4 && g_objXmlHttp.status == 200 && m_Search_Seccions[mv_intSearch_Num] == m_Search_Seccions[0]) {
            var objGeneralContent = getElementDHTML("div_obj_full_result_map");
            //var objGeneralContent = getElementDHTML("div_obj_full_result_map");
            var objXMLDoc = getXMLDocument("");
            if (isMozilla) {
                //var parser = new DOMParser();
                objXMLDoc = g_objXmlHttp.responseXML; //parser.parseFromString(g_objXmlHttp.responseText,"text/xml");
            }
            else {
                objXMLDoc.loadXML(g_objXmlHttp.responseText);

            }
            //objGeneralHidden.innerHTML = "";
            //objGeneralHidden.visible = false;
            m_objMapCoordenates = new Array();
            var objXSLDoc = getXMLDocument(getRootPath() + "Data/YP/yp_search_listing.xslt");
            transformAjaxXsl(objXMLDoc, objXSLDoc, "div_obj_full_result_map");

            //---------------------------------------------------------------
            //prepareVariables(objXMLDoc.selectNodes());
            removePoint();
            setTimeout(function() { LoadBounds() }, 0);

            //if (m_objMapCoordenates.length == 0)
            //prepareVariables(objXMLDoc.selectNodes("RootElement/General/Subscriber/Anuncios"));
            window.addEvent('domready',
        function() {
            Lightbox.init(
                    { descriptions: '.lightboxDesc',
                        showControls: true
                    }
                );
        }
        );

            return "";
        }
    } catch (e) { prompt("message", "ReadyState" + e); }

}

function AutoPositionAndZoom() {
    try {
        canSearch = false;

        var bounds = new GLatLngBounds();
        for (var i = 0; i < markers.length; i++) {
            try {
                if (markers[i] != null && !markers[i].isHidden()) {
                    var point = markers[i].getPoint(); //.getPoint();
                    bounds.extend(point);
                }
            }
            catch (ex) { }

        }
        map.setZoom(map.getBoundsZoomLevel(bounds));
        map.setCenter(bounds.getCenter());
    }
    catch (ex) { }
}


function trim(str) {
    try {
        return (("" + str).replace(/^\s*([\s\S]*\S+)\s*$|^\s*$/, '$1'));
    } catch (e) {
        ////alert(e.description)
        return;
    }
}
function replaceAll(pstrValue, pstrfind, pstrReplace) {
    try {
        var strValueF = new String();
        strValueF = pstrValue;
        while (strValueF.indexOf(pstrfind) > -1)
            strValueF = strValueF.replace(pstrfind, pstrReplace);

        return strValueF;
    } catch (e) {
        ////alert(e.description)
        return "";
    }

}
/*
Para Sincronizar la paginas con Ajax
param Method name by num 
*/
//debugger
function PagesSincronizer(p_intSearch_Num, p_strSearchID, p_map_latitud, p_map_longitud) {
    try {
        if (!m_Search_Seccions[p_intSearch_Num])
            return;
        mv_intSearch_Num = p_intSearch_Num;
        g_objXmlHttp.open("POST", getAjaxPath() + m_Search_Seccions[p_intSearch_Num], true);
        //g_objXmlHttp.open("POST",level + "ajaxServices/paelAjaxServer.asmx/"+m_Search_Seccions[p_intSearch_Num],false); 
        g_objXmlHttp.setRequestHeader("Content-Type", "Application/x-www-form-urlencoded; charset=UTF-8");
        var l_strParams = "";
        if (m_Search_Seccions[p_intSearch_Num] == m_Search_Seccions[0]) {
            l_strParams = "p_str_search_id=" + encodeURIComponent(p_strSearchID) + "&p_str_map_latitud=" + p_map_latitud + "&p_str_map_longitud=" + p_map_longitud;
        }
        else {
            l_strParams = params;
        }
        // Invoke Listing Data
        g_objXmlHttp.onreadystatechange = updateAjaxComplete;
        g_objXmlHttp.send(l_strParams);
        return "";
    } catch (e) {
        alert(e.description + "; sincroniza...");
        return;
    }
} // end of function 

function queryStringValue(findName) {
    var name = new String();
    var value = new String();
    var querystring = document.location.href;
    if (querystring.indexOf("?") == -1) {
        return "null";
    }
    querystring = querystring.split("?");
    querystring = querystring[1].split("&");
    for (q = 0; q < querystring.length; q++) {
        var pair = querystring[q].split("=");
        name = pair[0].toLowerCase();
        value = pair[1];
        if (findName.toLowerCase() == name) {
            return value;
        }
    }
}

/*
Valores de Ambiente
*/
function setGeneralData(p_name, p_class_code, p_class_name, p_city_code, p_city_name, p_page_num, p_search_type, p_search_action, p_lang_Code) {
    try {
        m_strSearch_data = p_name == "" ? "" : p_name; //getElementValue("__calle")
        m_strClass_Code = p_class_code == "" ? getElementValue("__class_code") : p_class_code;
        m_strClass_Name = p_class_name == "" ? getElementValue("__class_name") : p_class_name;
        m_strCity_Code = p_city_code == "" ? getElementValue("__class_code") : p_city_code;
        m_strCity_Name = p_city_name == "" ? getElementValue("__class_name") : p_city_name;
        m_strNew_Page = p_page_num == "" ? getElementValue("__class_name") : p_page_num;
        m_strLanguage_Code = p_lang_Code == "" ? getElementValue("__lang_code") : p_lang_Code;
        m_strSearchType = p_search_type == "" ? getElementValue("__search_type") : p_search_type;
        m_strSearchAction = p_search_action == "" ? getElementValue("__search_action") : p_search_action;
        //        alert(m_strSearch_data ); 
        return PagesSincronizer(1, null);
    } catch (e) {
        alert(e.description);
    }
    return "";
}
function LoadDataByName(p_field_name, p_field_value) {
    if (p_field_name == "Clasificado_code")//---    
        return setGeneralData("", p_field_value, "", "", "", "", "", "", "");
    else if (p_field_name == "City_code")
        return setGeneralData("", "", "", p_field_value, "", "", "", "", "");
    return "";
}
function getElementDHTML(p_strName) {
    var objElement;
    if (document.all) {
        objElement = document.all[p_strName];
    } else
        if (document.layers) {
        objElement = document.layers[p_strName];
    } else
        if (document.getElementById) {
        objElement = document.getElementById(p_strName);
    }
    return objElement;
}
function getElementValue(p_strName) {
    var objElement = getElementDHTML(p_strName);
    if (objElement) {
        return objElement.value;
    } else
        return "";
}
function setNodeValue(pobjNode, pstrField, pstrValue) {
    try {
        if (pobjNode.selectSingleNode(pstrField).firstChild != null)
            pobjNode.selectSingleNode(pstrField).firstChild.nodeValue = pstrValue;
        return true;
    } catch (e) {
        return false;
    }
}
function prepareVariables(p_objNodes) {
    if (p_objNodes == null)
        return;
    var lng = p_objNodes.length;
    if (isMozilla)
        lng = lng / 2;
    for (i = 0; i < lng; i++) {
        m_objMapCoordenates[i] = new Array();
        m_objMapCoordenates[i][0] = getNodeValue(p_objNodes[i], "Nombre");
        m_objMapCoordenates[i][1] = getNodeValue(p_objNodes[i], "Latitud");
        m_objMapCoordenates[i][2] = getNodeValue(p_objNodes[i], "Longitud");
        m_objMapCoordenates[i][3] = getNodeValue(p_objNodes[i], "@ID");
        m_objMapCoordenates[i][4] = getNodeValue(p_objNodes[i], "Full_link");
        m_objMapCoordenates[i][5] = getNodeValue(p_objNodes[i], "Class_code/@ID");
        m_objMapCoordenates[i][6] = getNodeValue(p_objNodes[i], "Class_code/@Class_name");
        m_objMapCoordenates[i][7] = getNodeValue(p_objNodes[i], "DIRECCION");
        m_objMapCoordenates[i][8] = getNodeValue(p_objNodes[i], "CIUDAD");
        m_objMapCoordenates[i][9] = getNodeValue(p_objNodes[i], "CITYNAME");
        m_objMapCoordenates[i][10] = getNodeValue(p_objNodes[i], "TELCODE");
        m_objMapCoordenates[i][11] = getNodeValue(p_objNodes[i], "TELEFONO");
        m_objMapCoordenates[i][12] = getNodeValue(p_objNodes[i], "EMAIL");
        m_objMapCoordenates[i][13] = getNodeValue(p_objNodes[i], "WEB");
        m_objMapCoordenates[i][14] = getNodeValue(p_objNodes[i], "ORDEN");
        m_objMapCoordenates[i][15] = getNodeValue(p_objNodes[i], "IMAP");
        m_objMapCoordenates[i][16] = getNodeValue(p_objNodes[i], "FOT1");
        m_objMapCoordenates[i][17] = getNodeValue(p_objNodes[i], "FOT2");
        m_objMapCoordenates[i][18] = getNodeValue(p_objNodes[i], "FOT3");
        m_objMapCoordenates[i][19] = getNodeValue(p_objNodes[i], "MMAP");
        m_objMapCoordenates[i][20] = getNodeValue(p_objNodes[i], "mapa");
    }
    return;
}

function SaveClick(cust_id, source, class_code) {
    var l_strParams = "cust_id=" + cust_id;
    l_strParams += "&source=" + source;
    l_strParams += "&class_code=" + class_code;
    PagesSincronizer(3, l_strParams);
}
function fillTable(secuencia, text, columnas) {
    var table = "";
    columnas--;
    if (secuencia == 0)
        table += "<tr><td style=\"vertical-align:top;\">" + text + "</td>";
    else if (secuencia % columnas == 0)
        table += "<td style=\"vertical-align:top;\">" + text + "</td></tr>";
    else if (secuencia % columnas != 0)
        table += "<td style=\"vertical-align:top;\">" + text + "</td>";
    return table;
}
function onGDirectionsLoad() {
    //resumen de tiempo y distancia
    document.getElementById("getDistance").innerHTML = gdir.getSummaryHtml();
}

function mostrarError() {
    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
        alert("No se ha encontrado una ubicación geográfica que se corresponda con la dirección especificada.");
    else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
        alert("No se ha podido procesar correctamente la solicitud de ruta o de códigos geográficos, sin saberse el motivo exacto del fallo.");
    else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
        alert("Falta el parámetro HTTP q o no tiene valor alguno. En las solicitudes de códigos geográficos, esto significa que se ha especificado una dirección vacía.");
    else if (gdir.getStatus().code == G_GEO_BAD_KEY)
        alert("La clave proporcionada no es válida o no coincide con el dominio para el cual se ha indicado.");
    else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
        alert("No se ha podido analizar correctamente la solicitud de ruta.");
    else alert("Error desconocido.");

}

function obtenerRuta(desde, hasta) {
    var i;
    var tipo;
    //comprobar tipo trayecto seleccionado
    /*for (i=0;i<document.form_ruta.tipo.length;i++){ 
    if (document.form_ruta.tipo[i].checked){
    break; 
    }
    } */
    //tipo = document.form_ruta.tipo[i].value;
    tipo = 2;
    if (tipo == 1) {
        //a pie
        gdir.load("from: " + desde + " to: " + hasta,
{ "locale": "es", "travelMode": G_TRAVEL_MODE_WALKING });
    } else {
        //conduccion
        gdir.load("from: " + desde + " to: " + hasta,
{ "locale": "es_DR", "travelMode": G_TRAVEL_MODE_DRIVING });
        //gdir.loadFromWaypoints(["36.5937, -121.88","38.299, -122.2836"]); 
    }

}

function viewFotMap(folder, image) {
    var width = 315;
    var height = 493;

    displayWindow('windowfotmap', '../', width, height, 1);
    document.getElementById("divfotmap").style.width = width.toString() + "px";
    document.getElementById("divfotmap").style.height = height.toString() + "px";

    document.getElementById("divfotmap").style.background = "url('http://ads.amarillas.com.do/FOT" + folder + "/" + image + ".jpg')";
}

function openDiv(frase, cont) {
    var span = "<a class=\"azul10mapa\">" + frase + ":</a>";
    span += "<br/>";
    span += "<div id=\"resultados\" style=\" border-style:solid; border-width:1px; border-color:#BFBFBF; width:940px; height:37px; background-color:white; position:absolute;\" onmouseover=\"javascript:document.getElementById('resultados').style.zIndex = document.getElementById('resultados').style.zIndex + 1; document.getElementById('resultados').style.height = ((document.getElementById('tableresult').style.height >= 37) ? document.getElementById('tableresult').style.height : 37);\" onmouseout=\"javascript:document.getElementById('resultados').style.zIndex = document.getElementById('resultados').style.zIndex - 1;document.getElementById('resultados').style.height = 37 + 'px';\">";
    span += "<table id=\"tableresult\" width=\"100%\">"
    document.getElementById('listapuntostd').style.height = 35 + "px";
    return span;
}

//Custom function for fetchng tiles from OSM server 
function TileToQuadKey(x, y, zoom) {
    var quad = "";
    for (var i = zoom; i > 0; i--) {
        var mask = 1 << (i - 1);
        var cell = 0;
        if ((x & mask) != 0)
            cell++;
        if ((y & mask) != 0)
            cell += 2;
        quad += cell;
    }
    return quad;
}

function sendMail(from, to, subject, fromName, message, toName, cliente, querystring) {
    var l_strParams = "from=" + from;
    l_strParams += "&to=" + to;
    l_strParams += "&subject=" + subject;
    l_strParams += "&fromName=" + fromName;
    l_strParams += "&message=" + message;
    l_strParams += "&toName=" + toName;
    l_strParams += "&cliente=" + cliente;
    l_strParams += "&querystring=" + encodeURIComponent(querystring);

    PagesSincronizer(2, l_strParams);
}
/*
* Para agregar un elemento al map (Para fines de Marcas)
*/
function addMapElement(p_int_Position, p_str_Nombre, p_float_Longitud, p_float_Latitud, p_str_Advert_id, p_str_adv_url, p_str_Advert_type, p_str_address_city, p_str_telephone, p_str_listing_type) {
    m_objMapCoordenates[p_int_Position - 1] = new Array();
    m_objMapCoordenates[p_int_Position - 1][0] = p_str_Nombre;
    m_objMapCoordenates[p_int_Position - 1][1] = p_float_Longitud;
    m_objMapCoordenates[p_int_Position - 1][2] = p_float_Latitud;
    m_objMapCoordenates[p_int_Position - 1][3] = p_str_Advert_id;
    m_objMapCoordenates[p_int_Position - 1][4] = p_str_adv_url;
    m_objMapCoordenates[p_int_Position - 1][5] = p_str_Advert_type;
    m_objMapCoordenates[p_int_Position - 1][6] = p_str_address_city;
    m_objMapCoordenates[p_int_Position - 1][7] = p_str_telephone;
    m_objMapCoordenates[p_int_Position - 1][8] = p_str_listing_type;
    return;
    // Como llamarla....
    /*<!-addMapElement(<xsl:value-of select="position()"/> - 1,'<xsl:value-of select="Nombre"/>',<xsl:value-of select="Longitud"/>,<xsl:value-of select="Latitud"/>,'<xsl:value-of select="@ID"/>','<xsl:call-template name="is_advert_listing_template"/>','<xsl:value-of select="Direccion"/>,<xsl:value-of select="Ciudad"/>','<xsl:value-of select="Telefonos/@ID"/>';*/
}