﻿// **************************************************************************************************
// * JScript File: PropertyLocator_Google_VirtualEarth_Maps.js                                      *
// **************************************************************************************************
// * Extracts all code related with construction/presentation of Google and/or Virtual Earth Maps   *
// * for a given listing.                                                                           *
// **************************************************************************************************
// * Rafael E. Martinez                                                 - Created on: July 23, 2007 *
// **************************************************************************************************
// * Change History                                                                                 *
// **************************************************************************************************
// * REM-1013 - 9/19/2007: Modify PropertyLocator.aspx page to include various features.            *
// **************************************************************************************************
// * Last working version number (without same icons on both maps): 29                              *
// **************************************************************************************************
<!--

    // Helper variables to highlight lines...    
    var onOne = true;
    var line = 0;
    var color = "";
    
    // Our map...
    var mapa;
    
    // Our icon base class...
    var baseicon = null;

    // Our GridView...
    var table = document.getElementById("ctl00_PageContent_gvwZestimates");

    // Tell us whether the satelite view was loaded and shown...
    var satloaded = false;                    

    function loadMap()
    {                                
        // Load Google Maps libraries only when there's an actual search...
        if (address != "")
        {
            if (typeof(GMap2) == "undefined" || typeof(loadGMap) == "undefined")
            {
                window.setTimeout(loadMap, 200);
            }
            else
            {
                // The value set in ms seems to be the 
                // required minimum to avoid bug with Firefox...
                window.setTimeout(loadGMap, 250);
            }
        }
    }
    
    function loadSat()
    {
        // Load VE Maps libraries only when there's an actual search...
        if (address != "")
        {                        
            if (typeof(VEMap) == "undefined" || typeof(VEMap.prototype.Init3D) == "undefined" || typeof(loadMSMap) == "undefined")
            {
                window.setTimeout(loadSat, 200);
            }
            else
            {
                window.setTimeout(loadMSMap, 200);               
            }
        }        
    }
    
    function pageLoad(sender, args) 
    {                           
        var script;                
        
        // Load maps libraries only when there's an actual search...
        if (address != "")
        {               
            // What browser is the user surfing on?
            if (issafari)
            {
                // Load the first custom VE Map code in the sequence when the browser is MAC's Safari...
                script = document.createElement("script");
                script.src = "/scripts/safari_ve_sequence_01.js";                
                script.type = "text/javascript";
                document.getElementsByTagName("head")[0].appendChild(script);
                
                // Load the custom VE Map control when the browser is MAC's Safari...
                script = document.createElement("script");
                script.src = "/scripts/mapcontrolv5Safari.js";
                script.type = "text/javascript";
                document.getElementsByTagName("head")[0].appendChild(script);
                
                // Load the second custom VE Map code in the sequence when the browser is MAC's Safari...
                script = document.createElement("script");
                script.src = "/scripts/safari_ve_sequence_02.js";                
                script.type = "text/javascript";
                document.getElementsByTagName("head")[0].appendChild(script);
                
                // Load the compatibility code when the browser is MAC's Safari...
                script = document.createElement("script");
                script.src = "/scripts/safaricompat.js";
                script.type = "text/javascript";
                document.getElementsByTagName("head")[0].appendChild(script);                
            }
            else
            {
                // Load Microsoft's VE Map control in the other cases...
                script = document.createElement("script");
                script.src = "http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=5";
                script.type = "text/javascript";
                document.getElementsByTagName("head")[0].appendChild(script);
            }
                        
            loadMap();
        }
    }
    
    function loadGMap()
    {
        // Do we have listing's coordinates...
        if (latitude == 0 || longitude == 0)
        {
            // No, we don't. Try to get map on the fly using listing's address...                                        
            var geocoder = new GClientGeocoder();
            var p = geocoder.getLatLng 
            (
                parseAddress(address), 
                function(point)
                {                    
                    if (point)
                    {                        
                        // Populate the global coordinates...                        
                        latitude = point.lat(); longitude = point.lng();                                                        

                        // Load Google's map then...
                        if (GBrowserIsCompatible())
                        {        
                            var geopoint = new GLatLng(latitude, longitude, true);                
                            loadGoogleMap(geopoint, 0);                                
                        }
                        else
                        {
                            var msg = "<div style='padding:20px'><b>Our apologies!</b><br /><br />Map view is not available for this address.</div>";
                            document.getElementById("dmap").innerHTML = msg;            
                        }
                                                                                
                        // Indicate the caller coordinates have been set...
                        return true;
                    }
                    else
                    {                                                                                                                
                        var msg = "<div style='padding:20px'><b>Our apologies!</b><br /><br />Map view is not available for this address.</div>";
                        document.getElementById("dmap").innerHTML = msg;                        
                        
                        // Indicate caller coordinates could not be set...
                        return false;
                    }                                        
                }
            );                        
        }
        else
        {            
            // Yes, we do. Load Google's map then...
            if (GBrowserIsCompatible())
            {        
                var geopoint = new GLatLng(latitude, longitude, true);                
                loadGoogleMap(geopoint, 0);                                
            }
            else
            {
                var msg = "<div style='padding:20px'><b>Our apologies!</b><br /><br />Map view is not available for this address.</div>";
                document.getElementById("dmap").innerHTML = msg;            
            }            
        }    
    }
    
    function loadMSMap()
    {
        if (!satloaded)
        {
            // Do we have the coordinates of the property...
            if (latitude != 0 && longitude != 0)
            {        
                // Yes, we do. Load Virtual Earth's map...
                showMSMap();
                satloaded = true;
            }
            else
            {
                // No, we don't. So we can't show VE Map...
                var msg = "<div style='padding:20px'><b>Our apologies!</b><br /><br />Satellite view is not available for this address.</div>";            
                document.getElementById("smap").innerHTML = msg;                        
            }        
        }
    }        
    
	function ToggleDZ() {}

	function cvtxtEMSG_ClientValidate(s,args)
	{
	    args.IsValid = true;	    
	    if (args.Value.length > 350)
	    {
	        args.IsValid = false;
        }
	}
		
	function parseAddress(address)
	{	    	    
        var retval = address;	        
        var w_add = "";
        
        var array = address.split("<br/>");
        	        
        for (var i = 0; i < array.length; i++)
        {
            w_add += array[i] + " ";
        }
        
        if (w_add != "")
        {	            
            retval = w_add;
        }
                
        return retval;	
	}    		
	
    function openTab(index, fromlink)
    {
        try
        {
            var tab = $find("ctl00_PageContent_tabContainer"); 
            if (tab == null)
            {                        
                setTimeout (function(){openTab(index, fromlink);}, 100);
                return false;
            }
            
            tab.set_activeTabIndex(index);
        }
        catch (e)
        {
            return false;                        
            alert("ERR:OPTAB " + e.message); // Letf here on purpose...        
        }                        
    }    
	
    function showMSMap()
    {
        var _tab = $find("ctl00_PageContent_tabContainer");        
        if(_tab == null)
        {                        
            setTimeout (function(){showMSMap();}, 100);
            return false;
        }
                
        var map = new VEMap("smap");
        try
        {
            map.AttachEvent("oninitmode", function(){getBirdsEye(map);});
            
            // Obtain active tab and memorize it...
            var at = _tab.get_activeTabIndex();
            
            // Make tab 2 visible to set virtual earth map...
            _tab.set_activeTabIndex(1);
            
            // Make a tiny dashboard...
            map.SetDashboardSize(VEDashboardSize.Tiny);
            
            // Load Microsoft's Virtual Earth map...            
            map.LoadMap(new VELatLong(latitude, longitude), 14, "h", false, VEMapMode.Mode2D, true);
                    
            // Add a pushpin to the property's location...            
            var pin = new VEShape(VEShapeType.Pushpin, new VELatLong(latitude, longitude));
            pin.SetTitle("Property searched:");
            pin.SetDescription(address);
            
            var text = "";            
            pin.SetCustomIcon("<div class=" + "\"pinStyle pinStyleMain\"" + "><div class=" + "\"texto\">" + "" + "</div></div>");
            map.AddShape(pin);
            
            var index = 1;                        

            // When the property is in zillow...
            if (zfound)
            {
                // Add also pushpins to the comparable recent sales...
                for (var i = 0; i < puntos.length; i++)
                {
                    var pin = new VEShape(VEShapeType.Pushpin, new VELatLong(puntos[i][0], puntos[i][1]));
                    
                    // Set bubble's title...
                    pin.SetTitle("Comparable sale:");
                    
                    // Want to show relevant information on the bubble...
                    var info = "<strong>Sold Price:</strong> ";
                    info += extractValueFromGrid(index, "Sold Price");
                    
                    info += "<br/>";
                    
                    info += "<strong>Zestimate Value:</strong> ";                
                    info += extractValueFromGrid(index, "Zestimate Value");
                       
                    // Also show a link to the property's address on the bubble...                                                                                
                    var lnk = info + "<br/>" + linkCreate(i, puntos[i][2]);
                                        
                    // Insert the link just created in the bubble...
                    pin.SetDescription(lnk);
                    
                    // Assign letters to all icons signaling properties...
                    pin.SetCustomIcon("<div class=" + "\"pinStyle\"" + "><div class=" + "\"texto\">" + puntos[i][3] + "</div></div>");                
                    
                    // Add the pushpin to the map...
                    map.AddShape(pin);                                                                                
                    index++;
                }            
            }           
            
            // Trap the mouse over event...
            map.AttachEvent ("onmouseover", onTheMouseOver);            
            
            // Trap the mouse click event...
            map.AttachEvent ("onclick", onMouseClick);

            // Obtain a reference to the map...
            mapa = map;
                                                                                    
            // Go back to the original active tab...
            _tab.set_activeTabIndex(at);                        
        }
        catch(e)
        {
            alert("ERR:VEMAP " + e.message);
        }                
    }
                            
    function getBirdsEye(map)
    {                     
        map.SetMapStyle(VEMapStyle.Birdseye);        
    }
        
    function onTheMouseOver(e)
    {
        // Having trapped the mouseover event, disabled it...
        return true;
    }    
    
    function onMouseClick(e)
    {    
        if (e.elementID != null)
        {
            try
            {
                var array = e.elementID.split("_");
                var index = Number(array[3].substring(3));                                                                                            
                
                if (index > 0)
                {
                    line = highlightLine(line, index, onOne);
                    onOne = false;
                }
                
                // Show the bubble at click of the mouse...                        
                mapa.ShowInfoBox(mapa.GetShapeByID(e.elementID));
            }
            catch (ex)
            {
                alert("ERR:MSECLK " + ex.message);
            }            
        }                                
    }
    
    function highlightLine(previous, current, onOne)
    {        
        try
        {
            if (!onOne)
            {                
                // Restore color of previous row...
                table.getElementsByTagName("tr")[previous].style.background = color;
            }
                                    
            // Obtain the color of current row...            
            color = table.getElementsByTagName("tr")[current].style.backgroundColor
                    
            // Highlight the row...            
            table.getElementsByTagName("tr")[current].style.background = "yellow";
        }
        catch (ex)
        {
            alert("ERR:HGHLNE " + ex.message);
        }                
                                    
        // Current row becomes previous...
        return current;
    }
                       
    function loadGoogleMap(geopoint, index)
    {
        var tab = $find("ctl00_PageContent_tabContainer"); 
        if (tab == null)
        {                        
            setTimeout (function(){loadGoogleMap(geopoint, index);}, 100);
            return false;
        }
        
        tab.set_activeTabIndex(index);			    
	    
        // Default map with blocks and streets...
        var map = new GMap2(document.getElementById("dmap"));
	        	    	    	    	    	    	    
        map.addControl(new GLargeMapControl());					    
        map.addControl(new GScaleControl());        
        map.setCenter(geopoint, 13);        
        map.setZoom(map.getZoom() + 1);
        
        // Create a marker icon right on the point, that 
        // will be our base icon for all of the markers, 
        // that specifies the shadow, icon dimensions, etc.
        baseicon = new GIcon();        
        baseicon.image = "../images/icons/map-pointer.gif";
        baseicon.iconAnchor = new GPoint(6, 28);
        baseicon.infoWindowAnchor = new GPoint(6, 6);

        // Show the bubble information window with address, above the point...        
        var marker = new GMarker(map.getCenter(), baseicon);
        map.addOverlay(marker);                
        
        var bubbletext = "<strong>Property searched:</strong><br/>" + address;
        GEvent.addListener (marker, "click", function() {marker.openInfoWindowHtml(bubbletext);});
        //marker.openInfoWindowHtml(bubbletext);

        // When the property is in zillow...
        if (zfound)
        {        
            // Plot the comparable recent sales...                        
            for (var i = 0; i < puntos.length; i++)
            {
                var p = new GLatLng(puntos[i][0], puntos[i][1], true);      
                map.addOverlay(createMarker(p, i, puntos[i][2]));
            }
        }
    }        

    function createMarker(point, index, address)
    {  
        // Create a lettered icon for this point using our icon base class...
        var letter = String.fromCharCode("A".charCodeAt(0) + index);
        var icon = new GIcon(baseicon);        
        icon.image = "../images2/pin_point" + letter + ".gif"                
                        
        // Index to access rows on GridView...
        var indice = index + 1;
                                
        var marker = new GMarker(point, icon);        
        GEvent.addListener
        (
            marker, "click", 
            function() 
            {
                line = highlightLine(line, indice, onOne);
                onOne = false;
                
                var info = "<strong>Sold Price:</strong> ";
                info += extractValueFromGrid(indice, "Sold Price");
                
                info += "<br/>";
                
                info += "<strong>Zestimate Value:</strong> ";                
                info += extractValueFromGrid(indice, "Zestimate Value");
                                                
                // Also show a link to the property's address on the bubble...                                    
                info += "<br/>" + linkCreate(index, address);
                
                marker.openInfoWindowHtml("<strong>Comparable sale:</strong><br/>" + info);
            }
        );
                        
        return marker;
    }
    
    function linkCreate(index, address)
    {
        var retval = "<a href='/Locate/";
        
        // Encode and format address as necessary...
        retval += "?address=" + escape(puntos[index][4]);
        var citystate = puntos[index][5].split(", ");
        retval += "&citystate=" + escape(citystate[0]) + escape(" ") + escape(citystate[1]);
        retval += "&zip=" + escape(puntos[index][6]) + "'>";

        // Do not show the address...
        retval += "More information" + "</a>";
                
        // Return the well-formed link...
        return retval;
    }

    function zpidLinkCreate(zpid)
    {
        var retval = "<a href='/locate/";
        retval += "?zpid=" + escape(zpid) + "'>";
        
        retval += "More information";
        retval += "</a>";
                
        // Return the well-formed link...
        return retval;        
    }
               
    function extractValueFromGrid(row, header)
    {
        var hds = table.getElementsByTagName("th")
        
        var col;        
        for (col = 0; col < hds.length; col++)
        {                        
            if (hds[col].innerHTML.toLowerCase() == header.toLowerCase())
            {                
                break;
            }            
        }
                
        return table.rows[row].cells[col].innerHTML;
    }    

    function addressExtract(address)
    {                
        var retval = "";
        var array = address.split("<br/>");
                
        retval = array[0] + "#";
        
        var city = array[1].split(",");        
        retval += city[0];
                
        var state = city[1].split(" ");        
        retval += " " + state[1] + "#" + state[2];
                                   	                        
        return retval
    }
    
    // REM-1013 >>>
    // Move an element directly on top of another element (and optionally make it the same size)...
    function Cover(bottom, top, ignoreSize) 
    {
        var location = Sys.UI.DomElement.getLocation(bottom);
        top.style.position = "absolute";
        top.style.top = location.y + "px";
        top.style.left = location.x + "px";
        if (!ignoreSize) 
        {
            top.style.height = bottom.offsetHeight + "px";
            top.style.width = bottom.offsetWidth + "px";
        }
    }
    // REM-1013 <<<
// -->