﻿    // JScript File
var map = null;
var bounds = null;
var markers = new Array();
var htmls = new Array;
var tooltip = document.createElement("div");
var orgHeight;
var async_count = 0;
var startTime = 0;
var statusMsgs = false;
var startPos = null;
var points = new Array();
var zoomLimited = false;

showLoadingMessage(true);

function load() 
{       
    //If we are just displaying the No Entries Graphic then we are done... 
    var noPropertiesImg = document.getElementById('mySpl_ctl01_ctl01_imgNoEntries');
    if (noPropertiesImg != null) 
    {
        mySpl.CollapsePanel('left');
        showLoadingMessage(false);
        return;
    }
        
    if (GBrowserIsCompatible()) 
    {
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl()); 
        map.addControl(new GScaleControl());
        
        if (readQueryString("nozoom").length == 0)
        {
            map.enableScrollWheelZoom();
            map.enableContinuousZoom();
        }       
   
        if (readQueryString("debug").length > 0)
        {
            statusMsgs = true;
            document.getElementById("floatDebug").style.visibility = "visible";
            GEvent.addListener(map, "click", function(marker, point){
                if (point) {
                        var lat = point.lat();
                        var lon = point.lng();
                        var display = lat + " , " + lon;
                        map.openInfoWindow(map.getCenter(), document.createTextNode(display));
                }
            });           
        }      
           
        //  ======== Add a map overview ==========
        map.addControl(new GOverviewMapControl(new GSize(150,150)));                     
                      
        // ====== set up marker mouseover tooltip div ======    
        map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
        map.setCenter(new GLatLng(37.062500, -95.677068), 4); 
        bounds = new GLatLngBounds();
        points.splice(0, points.length);               
    }
    
    if (document.getElementById('NeighborhoodSelected').value.length > 0)
    {
        mySpl.CollapsePanel('left');
        var neighborhood = document.getElementById('NeighborhoodSelected').value.replace(/ /g, '_');
        var elem = document.getElementById('chk_' + neighborhood);
        if (elem != null)
            elem.click();
    }
        
    clearFloat();
    tooltip.style.visibility="hidden";    
    showLoadingMessage(false);
    
    orgHeight = getHeight();
    window.onresize = redo;  
}


function getHeight()
{
    var myHeight = 0;
    if (typeof(window.innerHeight) == 'number') 
        myHeight = window.innerHeight;
    else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) 
        myHeight = document.documentElement.clientHeight;
    else if (document.body && (document.body.clientWidth || document.body.clientHeight)) 
        myHeight = document.body.clientHeight;
        
    return myHeight;
}

//Reload the window on a resize event
function redo() 
{   
    var newHeight = getHeight();
    if (orgHeight != newHeight)
    {        
        //Ignore popup warnings bar adjustments. 
        if ((newHeight < orgHeight) && (newHeight + 32 > orgHeight))
            return;
        orgHeight = newHeight;
        location.href = location.href;
    }
}
     
//Clear the floating choice list
function clearFloat()
{
   if (document.getElementById('floatingChoices'))
        document.getElementById('floatingChoices').style.visibility = 'hidden';
   
   if (document.getElementById('div_floatCancelButton'))
        document.getElementById('div_floatCancelButton').style.visibility = 'hidden';
}       

 
//Mark the status of the amenity as "D" in the database
function removeObject(nodeID)
{
    map.closeInfoWindow();
    if (confirm("Are you sure you wish to remove this amenity?"))
    { 
        var marker = markers[nodeID.name];
        if (marker != null)
        {
            tooltip.style.visibility="hidden";
            map.removeOverlay(marker);
            markers[nodeID.name] = null;
        }
        ob_t2_Remove(nodeID.name);
        var userId = document.getElementById('UserId').value;
        PageMethods.RemoveAmenity(nodeID.name, userId);                
    }
}

// A function to create the marker with a tooltip
function createMarker(point, name, html, nodeID, category) 
{
    //Just a test
    if (points[point] != null)
    {
        while (points[point] != null)
        {
            point.y += .0001;
            point.x -= .0001;    
            point = new GLatLng(point.y, point.x);
        }
    }
    
    var body = html.replace(/<BR \/>/i, ' - ').replace(/<br\/>/i, ' - ');
    if (body.indexOf("<IMG") != -1)
    {
        var last = body.indexOf("/>");
        body = body.substr(last + 2);
    }
    html = '<div align="left" style="white-space:nowrap;font-family: Arial;font-size: 10pt;"><br/>' + html + '</div>';
     
    var imagePath = "images/" + category + ".png";
    if (category.length == 0)
        imagePath = "";
    var myIcon = new GIcon();
    myIcon.image = imagePath;
    myIcon.iconAnchor = new GPoint(20, 32);
    myIcon.infoWindowAnchor = new GPoint(16, 5);
    myIcon.iconSize= new GSize(39,34);
    myIcon.shadow = "images/shadow-" + category + ".png";
    myIcon.shadowSize = new GSize(41,36);
     
    // === marker with tooltip ===
    var marker;
    
    if (document.getElementById("Realtor").value == "Y")
    {
        marker = new GMarker(point, {icon:myIcon, draggable:true});
        GEvent.addListener(marker, "dragstart", function() 
            {
                startPos = marker.getLatLng();
                map.closeInfoWindow();
            });            
                
        GEvent.addListener(marker, "dragend", function() 
            {
                moveHome(marker, nodeID);
            });    
    }
    else
        marker = new GMarker(point, {icon:myIcon, draggable:false} );                    
    
    GEvent.addListener(marker, "click", function() {
        tooltip.style.visibility="hidden";
        marker.openInfoWindowHtml(html);
    });

    marker.tooltip = '<div class="tooltip">'+name+'</div>';
    // ===========================

    
    //  ======  The new marker "mouseover" and "mouseout" listeners  ======
    GEvent.addListener(marker,"mouseover", function() {
      showTooltip(marker);
    });        
    
    GEvent.addListener(marker,"mouseout", function() {
	tooltip.style.visibility="hidden"
    });           

    map.addOverlay(marker);
    markers[nodeID] = marker;
    htmls[nodeID] = html;
    
    points[point] = nodeID;
    bounds.extend(point);
    map.setZoom(map.getBoundsZoomLevel(bounds));
    map.setCenter(bounds.getCenter());
    
    if (zoomLimited == false)
    {
        // ====== Restricting the range of Zoom Levels =====
        var mt = map.getMapTypes();
        for (var i=0; i<mt.length; i++) 
            mt[i].getMinimumResolution = function() { return 12; }                           
            
        zoomLimited = true;
    }  
  }
  
  //Allow the admin to move the marker to a new location
  function moveHome(marker, nodeID)
  {     
    if (confirm("Are you sure you wish to move the home to this new position?"))
    {
        var pointNew = marker.getLatLng(); 
        var propertyID = nodeID.replace('property_', '');
        PageMethods.MoveHome(propertyID, pointNew.y, pointNew.x);
    }
    else
    {
        //Move the marker back to original position
        marker.setLatLng(startPos);          
    }
}


function showLoadingMessage(bShow)
{
    var waitImage = document.getElementById("waitImage");
    if (bShow)
    {
        if (waitImage != null)
            waitImage.style.visibility="visible";         
    }
    else
    {
        //Wait till the last process is complete
        if (async_count > 0)
            async_count--;
        if (async_count == 0)
        {
            if (waitImage != null)
                waitImage.style.visibility="hidden";
        }
    }
}
 
// ====== This function displays the tooltip ======
// it can be called from an icon mousover or a sidebar mouseover
function showTooltip(marker) 
{
    tooltip.innerHTML = marker.tooltip;
    var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
    var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getLatLng(),map.getZoom());
    var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
    var height=tooltip.clientHeight;
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height)); 
    pos.apply(tooltip);
    tooltip.style.visibility="visible";
  }


//Event handler for category check box selection
function neighborhoodClick(e)
{   
    map.closeInfoWindow();
    updateStatus("Loading node.", true);
    var filter = "";
    
    // To check/uncheck checkboxes in children.
    if (ob_hasChildren(e.parentNode)) 
    {
	    var ob_t2in=e.parentNode.parentNode.parentNode.parentNode.nextSibling.getElementsByTagName("input");
	    for (var i=0; i<ob_t2in.length; i++) 
	    {
		    if (e.checked != ob_t2in[i].checked) 
		    {		    
		        ob_t2in[i].checked = e.checked;
		        propertyClick(ob_t2in[i]);
    	    }
	    }
    }
    
    if (e.checked==false) 
        ob_t2_unchk_parent(e.parentNode);

}
  
//Handle a propertyClick
function propertyClick(e)
{
    updateStatus("Loading node.", true);  
    var nodeID = e.id.replace('chk_', 'property_');
    var PCID = document.getElementById("PCID").value;
    var marker = markers[nodeID]; 
    if (e.checked)
    {        
        if (marker == null)
        {
            var detailLink = "";
            var point = new GLatLng(ob_t2_Data[nodeID].Latitude, ob_t2_Data[nodeID].Longitude);
            var name = ob_t2_Data[nodeID].Name;
            var html = "<table><tr><td colspan='3'><div align='center' style='font-weight:bold; color:Blue; font-size:Large;'>";
            var link = "<a target='_blank' href='Default.aspx?propertyID=" + ob_t2_Data[nodeID].PropertyGuid + "&PCID=" + PCID + "&address=" + escape(ob_t2_Data[nodeID].Name) + "' >";                        
            //Explicit exception for The Homestead Group only...
            if (ob_t2_Data[nodeID].DisplayURL.length > 0)
                detailLink = "<a target='_parent' href='" + ob_t2_Data[nodeID].DisplayURL + "' >";            
            else
                detailLink = "<a target='_blank' href='Embedded.aspx?propertyID=" + ob_t2_Data[nodeID].PropertyGuid + "&PCID=" + PCID + "' >";
            html += detailLink + name + "</a></div></td></tr>";   
            if (ob_t2_Data[nodeID].ImageURL.length > 0)
            {
                html += '<td rowspan="5">' + link + '<IMG src=\"'; 
                html += ob_t2_Data[nodeID].ImageURL + '\" width=100 height=75 align=left /></a></td>';
            }            

            if (ob_t2_Data[nodeID].AvailableDate.length > 0)
                html += '<tr><td align="left">' + ob_t2_Data[nodeID].AvailableDate + '</td></tr>';
            
            if (ob_t2_Data[nodeID].BuildingType.length > 0)
                html += '<tr><td align="left">Building: ' + ob_t2_Data[nodeID].BuildingType + '</td></tr>';
            html += '<tr><td align="left">' + ob_t2_Data[nodeID].Price + '</td></tr>';
            html += '<tr><td align="left">' + ob_t2_Data[nodeID].Beds + ' Beds, ' + ob_t2_Data[nodeID].Baths + ' Baths</td></tr>';
            html += '<tr><td align="left">Pets: ' + ob_t2_Data[nodeID].Pets + '</td></tr>';
            html +=  '<tr><td>' + detailLink + 'More Info</a></td><td>' + link + 'Amenity Map</a></td></tr>';
            html += '</table>';

            var img = "marker_small";
            switch (ob_t2_Data[nodeID].BuildingType.toLowerCase())
            {
                case "townhouse":
                case "single family home":
                case "coach house":
                case "other":
                    img = "marker_small";
                    break;
                case "walkup":
                case "condo":
                case "loft":
                case "duplex":
                case "corridor building":
                case "courtyard building":
                    img = "marker_med";
                    break;
                case "high-rise":
                case "mid-rise":
                    img = "marker_large";
                    break;                    
            }  
            //This is notion pools then we are doing the homestead bubble
            if (PCID.toUpperCase()  == '78348DCF-2D56-4B65-B159-E8B68A9A0288')
            {  
                var url = 'http://www.thehomesteadgroup.com/snippet.asp?P='; // + nodeID;
                url += ob_t2_Data[nodeID].MLSID + '|';
                url += nodeID.replace('property_', '') + '|';
                url += ob_t2_Data[nodeID].PropertyGuid + '|';
                var beds = ob_t2_Data[nodeID].Beds + ' Bed / ';
                var baths = ob_t2_Data[nodeID].Baths.split('.');
                beds += baths[0] + ' Bath';
                if (baths[1] > 0)
                    beds += ' / ' + baths[1] + ' Half Bath';
                url += beds + '|';
                url += ob_t2_Data[nodeID].Neighborhood + '|';
                url += ob_t2_Data[nodeID].Street.replace('&', '%26') + '|';
                url += ob_t2_Data[nodeID].AvailableDate + '|';
                url += ob_t2_Data[nodeID].Price + '|';
                url += ob_t2_Data[nodeID].ImageURL + '|';
                url += ob_t2_Data[nodeID].Description.replace('&', '%26') + '|';
                url += ob_t2_Data[nodeID].Heat + '|';
                url += ob_t2_Data[nodeID].AC + '|';
                url += ob_t2_Data[nodeID].Dish + '|';
                url += ob_t2_Data[nodeID].Laundry + '|';
                url += ob_t2_Data[nodeID].Floor + '|';
                url += ob_t2_Data[nodeID].Fire + '|';
                var parking = ob_t2_Data[nodeID].Park;
                if (parking == '1.1')
                    url += 'Available (Garage)|';
                else if (parking = '0.1')
                    url += 'Available|';
                else
                    url += 'Street|';
                                
                url += ob_t2_Data[nodeID].Pets + '|';
                                
                PageMethods.GetWebPage(url, function(results) 
                {
                    if (results.length > 0)
                        html = results;
                    createMarker(point, name, html, nodeID, img);
                });
            }
            else
                createMarker(point, name, html, nodeID, img);                        
        } 
        else if (marker.isHidden())
            marker.show();                        
    }
    else if (marker != null && marker.isHidden() == false)
    {
        map.closeInfoWindow();
        tooltip.style.visibility="hidden";
        marker.hide();
        
        //Reset the bounds if we are hiding the marker
        bounds = new GLatLngBounds();
        points[point] = null;
        for (var pnt in markers)
        {
            var addMarker = markers[pnt];
            if (addMarker.isHidden() == false)
                bounds.extend(addMarker.getLatLng());
        }
           
        if (!bounds.isEmpty())    
        {
            map.setZoom(map.getBoundsZoomLevel(bounds));
            map.setCenter(bounds.getCenter());
        }
    }    
}


//Display the tool tip based on the markers ID
function st(marker_id)
{
    marker_id = marker_id.replace('chk', 'property');
    var marker = markers[marker_id];
    if (marker != null && !marker.isHidden()) //&& (overlay[marker_id] != null))   
        showTooltip(marker);
}

//Hide the tooltip
function ht()
{
    tooltip.style.visibility="hidden";
}

function sn(marker_id)
{
    map.closeInfoWindow();
    marker_id = marker_id.replace('chk', 'property');
    
    var marker = markers[marker_id];
    if (marker != null && !marker.isHidden()) //&& (overlay[marker_id] != null))  
        marker.openInfoWindowHtml(htmls[marker_id]);
}
  
//Read the query string and return the keys value
function readQueryString(key)
{ 
    var qs = location.search.substring(1,location.search.length)
    //There was no query string we are done
    if (qs.length == 0) 
        return "";

    qs = qs.replace(/\+/g, ' ');
    var args = qs.split('&');
	
    // split out each name=value pair
    for (var i=0;i<args.length;i++) 
    {
        var pair = args[i].split('=');
	    var name = unescape(pair[0]);
	   
	    if (name == key)
	    {
	        if (pair.length == 2)
		        return unescape(pair[1]);
	        else
		        return "";
        }    		
    }
    return "";
}

function updateStatus(message, reset)
{
    if (!statusMsgs)
        return;

    var status = document.getElementById("lblStatus");
    var now = new Date();            
    
    if (reset)
        startTime = now.getTime();
     
    var now = new Date();
    var fromStart = (now.getTime() - startTime) / 1000;
            
    status.innerHTML += "&nbsp;&nbsp;" + fromStart + ": " + message + "<br />"    
}


//Return all of the checked items by the type
function checked_list(chkType) 
{
	// Make string with checked checkboxes IDs.	
	var ob_t2in,ob_t2s,ob_t2checked="";
	ob_t2in=document.getElementsByTagName("input");
	for (var i=0; i<ob_t2in.length; i++) {
		ob_t2s=ob_t2in[i].id;
		if ((ob_t2s.substr(0,chkType.length)==chkType) && (ob_t2in[i].checked)) {
			ob_t2checked=ob_t2checked+ob_t2s+",";
		}
	}
	return ob_t2checked;
}
