﻿// JScript File
// Encapsulates the code for displyaing goole maps 

/*------------------------------------------------------------------------------------------------*/
/* Variable Declaration
/*------------------------------------------------------------------------------------------------*/

    var map;
    var Lat;
    var Long; 
    var MarkerPoints=[];
    var TabMarkersHTML=[]; 
    var TabLables=[];
    var markers=[];
    var PropMarkers ;                    
    var arrPropMarkers = [];                    
    var bounds = new GLatLngBounds();
    var cnt = 0;
    var CurrZoom = 0;
    var PrevZoom = 0;
    var TotProps = 0;
    var mapXML = "";
    var CenLat = 0;
    var CenLong = 0;
    var InitialPass = true;
    
/*------------------------------------------------------------------------------------------------*/
/* Open Map, Set Bounderies, Zoom To Default, And Assign First Icons
/*------------------------------------------------------------------------------------------------*/

    function ChangeCriteria()
    { 
        var MapType = document.getElementById('MapType');
        
        if(MapType.value == "multiple")
        {
            if(CenLat != map.getCenter().lat() && CenLong != map.getCenter().lng() || CurrZoom != PrevZoom )
            {
                CenLat = map.getCenter().lat();
                CenLong = map.getCenter().lng();
                InitialPass = false;
                var SearchType = document.getElementById('SearchType').value;    
                if(SearchType == "property")
                {
                    loadProps("", "");
                }
                else if(SearchType == "branch")
                {
                    loadBranches();
                }
                PrevZoom = CurrZoom;   
            }
        }
    }
      
    function loadMap()
    {  
        map = new GMap2(document.getElementById('divMap'));
        
        var CenLatLng = new GLatLng(52.485338, -1.861533 );                                                           
        map.setCenter(CenLatLng,5);
        map.addControl(new GMapTypeControl());
		map.addControl(new GLargeMapControl());
		map.enableContinuousZoom();
        
        var SearchType = document.getElementById('SearchType').value;
        if(SearchType == "property")
        {
            loadProps("", "");
        }
        else if(SearchType == "branch")
        {
            loadBranches();
        }
        
        document.getElementById('InitialSearch').value = "false";             
    }
    
    function loadProps(minPrice, maxPrice)
    { 
        document.getElementById('loadingMap').style.display = 'block';
        //map.clearOverlays();              
        TotProps = 0;
        var SearchType = document.getElementById('SearchType').value;
        var transType = document.getElementById('TransType').value;  
        var branchID = document.getElementById('BranchID').value;
        var SearchCrit = "?InitialSearch=" + document.getElementById('InitialSearch').value
                        + "&SWLat=" + map.getBounds().getSouthWest().lat()
                        + "&SWLng=" + map.getBounds().getSouthWest().lng()
                        + "&NELat=" + map.getBounds().getNorthEast().lat()
                        + "&NELng=" + map.getBounds().getNorthEast().lng()
                        + "&minPrice=" + minPrice
                        + "&maxPrice=" + maxPrice
                        + "&DisplayType=" + document.getElementById('DisplayType').value
                        + "&TransType=" + transType 
                        + "&branchID=" + branchID
                        + "&dummy=" + (new Date()).getTime();
                       
	    GDownloadUrl("/properties/map-points.aspx" + SearchCrit, function(mapXML, responseCode) {
	    
            // obtain the array of markers and loop through it
            if(responseCode == 200) 
            {                
                map.clearOverlays();
                var xml = GXml.parse(mapXML); 
                markers = xml.documentElement.getElementsByTagName("mkr");
                var iMarker = 0;
                var NoMarkers = markers.length;
                var detailFolder  = "/properties-for-sale/" 
                if (transType == "rent")
                {
                    detailFolder  = "/properties-for-rent/" 
                } 
                for (iMarker = 0; iMarker < NoMarkers; iMarker++) 
                { 
                    Lat = markers[iMarker].getAttribute("lt");
                    Long = markers[iMarker].getAttribute("lg");
                    MarkerPoints[iMarker] = new GLatLng(Lat,Long);
                    
                    if(MarkerPoints[iMarker] != null)
                    { 
                        var props = markers[iMarker].getElementsByTagName("prop");
                        
                        //Get rid of props that should not be displayed  
                        var houseChecked = document.getElementById('house').checked 
                        var apartmentChecked = document.getElementById('apartment').checked
                        var bungalowChecked = document.getElementById('bungalow').checked
                        var landChecked = document.getElementById('land').checked                         
                        var NoProps = props.length;
                        
                        var displayProps = [];
                        var displayPropIndex = 0;
                        for (iProp = 0; iProp < NoProps; iProp++)
                        {          
                            var type = props[iProp].getAttribute("type");
                            var displayProp = false;
                            if(type == "house" && houseChecked == true)displayProp = true;
                            if(type == "apartment" && apartmentChecked == true)displayProp = true;
                            if(type == "bungalow" && bungalowChecked == true)displayProp = true;
                            if(type == "land" && landChecked == true)displayProp = true;
                            
                            if(displayProp)
                            {
                                displayProps[displayPropIndex] = props[iProp];
                                displayPropIndex++;
                            }
                        }
                          
                        
                        var iProp = 0;                         
                        var NoProps = displayProps.length;
                        TotProps += NoProps;
                        TabMarkersHTML = [];
                        TabLables = [];
                        for (iProp = 0; iProp < NoProps; iProp++)
                        {                
                            var beds = displayProps[iProp].getAttribute("bds");
                            var thumb = displayProps[iProp].getAttribute("img");
                            var price = displayProps[iProp].getAttribute("pr");
                            var addr = displayProps[iProp].getAttribute("ad");
                            var propLink = detailFolder + displayProps[iProp].getAttribute("lk"); 
                            var type = displayProps[iProp].getAttribute("type");
                            
                            var html = GenerateHTML(SearchType, beds, thumb, price, addr, propLink);
                            if (NoProps == 1)
                            {
                                 PropMarkers = CreatePropMarker(MarkerPoints[iMarker], html, CreateIcon(type), type + " in this location");
                            }
                            else
                            {
                                delete PropMarkers;
                                TabMarkersHTML[iProp] = html;
                                TabLables[iProp] = "Property " + (iProp+1);
                                var MarkerToolTip = (iProp + 1) + " Properties in this location";
                                PropMarkers = CreateTabbedPropMarker(MarkerPoints[iMarker], TabMarkersHTML,TabLables,CreateIcon("multiple"), MarkerToolTip);                                
                            }
                        }
                                                           
                        map.addOverlay(PropMarkers);
            
                        // Extend map bounds to include the new marker 
                        bounds.extend(MarkerPoints[iMarker]);         
                    }
                }
                
                //Display the number of properties
                document.getElementById('lblNoOfProperties').innerHTML = MapTitle(SearchType, "", TotProps);
                
                if(InitialPass == true)
                { 
                    // determine the centre from the bounds 
                    CenLat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
                    CenLong = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
                    if(TotProps == 1)
                    {
                        CurrZoom = 15;
                    }
                    else
                    {
                        CurrZoom = map.getBoundsZoomLevel(bounds);
                    }
                }
                var Coords = new GLatLng(CenLat,CenLong);           
                map.setCenter(Coords, CurrZoom);
                delete Coords;
                document.getElementById('loadingMap').style.display = 'none'; 
            }
            mapXML = "";  
         
            var ZoomEvent = GEvent.addListener(map, "zoomend", function(oldzoom, newzoom){
                CurrZoom = newzoom;
                ChangeCriteria();
                GEvent.removeListener(ZoomEvent);
            });
            
            var DragEvent = GEvent.addListener(map, "dragend", function(){
                CurrZoom = CurrZoom;
                ChangeCriteria();
                GEvent.removeListener(DragEvent);
            });
        }); 
        delete MarkerPoints;
    }   
    
    function loadBranches()
    { 
        document.getElementById('loadingMap').style.display = 'block';
        //map.clearOverlays();              
        TotBranches = 0;
        var SearchType = document.getElementById('SearchType').value;
        
        var SearchCrit = "?InitialSearch=" + document.getElementById('InitialSearch').value
                        + "&SWLat=" + map.getBounds().getSouthWest().lat()
                        + "&SWLng=" + map.getBounds().getSouthWest().lng()
                        + "&NELat=" + map.getBounds().getNorthEast().lat()
                        + "&NELng=" + map.getBounds().getNorthEast().lng()
                        + "&dummy=" + (new Date()).getTime();
                       
	    GDownloadUrl("/contact-us/map-points.aspx" + SearchCrit, function(mapXML, responseCode) {
	    
            // obtain the array of markers and loop through it
            if(responseCode == 200) 
            {        
                map.clearOverlays();        
                var xml = GXml.parse(mapXML); 
                markers = xml.documentElement.getElementsByTagName("mkr");
                var iMarker = 0;
                var NoMarkers = markers.length;
                  
                for (iMarker = 0; iMarker < NoMarkers; iMarker++) 
                { 
                    Lat = markers[iMarker].getAttribute("lt");
                    Long = markers[iMarker].getAttribute("lg");
                    MarkerPoints[iMarker] = new GLatLng(Lat,Long);
                    
                    if(MarkerPoints[iMarker] != null)
                    { 
                        var branches = markers[iMarker].getElementsByTagName("branch");
                        var iBranch = 0;                         
                        var NoBranches = branches.length;
                        TotBranches += NoBranches;
                        TabMarkersHTML = [];
                        TabLables = [];
                        for (iBranch = 0; iBranch < NoBranches; iBranch++)
                        {                
                            var thumb = branches[iBranch].getAttribute("img");
                            var addr = branches[iBranch].getAttribute("ad");
                            var branchLink = branches[iBranch].getAttribute("lk"); 
                            //var type = "branch";
                            var type = "house";
                            
                            var html = GenerateHTML(SearchType, "", thumb, "", addr, branchLink);
                            if (NoBranches == 1)
                            {
                                 BranchMarkers = CreatePropMarker(MarkerPoints[iMarker], html, CreateIcon(type), "branch in this location");
                            }
                            else
                            {
                                delete BranchMarkers;
                                TabMarkersHTML[iBranch] = html;
                                TabLables[iBranch] = "Branch " + (iBranch+1);
                                var MarkerToolTip = (iBranch + 1) + " Branches in this location";
                                BranchMarkers = CreateTabbedPropMarker(MarkerPoints[iMarker], TabMarkersHTML,TabLables,CreateIcon(type), MarkerToolTip);                                
                            }
                        }
                                                           
                        map.addOverlay(BranchMarkers);
            
                        // Extend map bounds to include the new marker 
                        bounds.extend(MarkerPoints[iMarker]);         
                    }
                }
                
                //Display the number of branches
                //document.getElementById('lblNoOfBranches').innerHTML = MapTitle(SearchType, "", TotBranches);
                
                if(InitialPass == true)
                { 
                    // determine the centre from the bounds 
                    CenLat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
                    CenLong = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
                    if(TotBranches == 1)
                    {
                        CurrZoom = 15;
                    }
                    else
                    {
                        CurrZoom = map.getBoundsZoomLevel(bounds);
                    }
                }
                var Coords = new GLatLng(CenLat,CenLong);           
                map.setCenter(Coords, CurrZoom);
                delete Coords;
                document.getElementById('loadingMap').style.display = 'none'; 
            }
            mapXML = "";  
         
            var ZoomEvent = GEvent.addListener(map, "zoomend", function(oldzoom, newzoom){
                CurrZoom = newzoom;
                ChangeCriteria();
                GEvent.removeListener(ZoomEvent);
            });
            
            var DragEvent = GEvent.addListener(map, "dragend", function(){
                CurrZoom = CurrZoom;
                ChangeCriteria();
                GEvent.removeListener(DragEvent);
            });
        }); 
        delete MarkerPoints;
    }
    
    
/*------------------------------------------------------------------------------------------------*/
/*  Generates popup Html for marker    	                                                          */
/*------------------------------------------------------------------------------------------------*/
    function GenerateHTML(SearchType, beds, thumb, price, addr, propLink)
    {
        var HTML = "";
        
        if(SearchType == "branch")
        {
            HTML = "<table><tr><td>"
                 + "<img src='" + thumb 
                 + "' width='147' height='100' /></td>" 
                 + "<td width='10'>&nbsp;</td><td  valign='top' align='right' nowrap><font color='black' size='2px'><b>" 
                 + addr 
                 + "</b>" 
                 + "<br /><br /> <a href='" + propLink 
                 + " ' target='_blank' >Branch details</a></font></td>" 
                 + "</tr></table>";
        }
        else if(SearchType == "House")
        {
            HTML = "<table><tr><td></td>" 
                 + "<td width='10'>&nbsp;</td><td  valign='top' align='right' nowrap><font color='black' size='2px'><b>" 
                 + addr 
                 + "</b><br /><br /></font></td>" 
                 + "</tr></table>";
        }   
        else if(SearchType == "MMLand")
        { 
            HTML = "<table><tr><td>"
                 + "<img src='" + thumb 
                 + "' width='147' height='100' /></td>" 
                 + "<td width='10'>&nbsp;</td><td  valign='top' align='right' nowrap><font color='black' size='2px'><b>" 
                 + addr 
                 + "</b><br />" + price 
                 + "<br /><br /> <a href='" + propLink 
                 + " ' target='_blank' >More photos and full details</a></font></td>" 
                 + "</tr></table>";
        }
        else
        {
            HTML = "<table><tr><td>"
                 + "<img runat='server' src='" + thumb 
                 + "' width='147' height='100' /></td>" 
                 + "<td width='60'>&nbsp;</td><td  valign='top' align='right' nowrap><font color='black' size='2px'><b>" 
                 + addr 
                 + "</b>" 
                 + "<br /> Number of Bedrooms : " + beds 
                 + " <br />" + price 
                 + "<br /><br /> <a href='" + propLink 
                 + " ' target='_blank' >More photos and full details</a></font></td>" 
                 + "</tr></table>";
        }  
                        
        return HTML;
    }

/*------------------------------------------------------------------------------------------------*/
/*  Generates the Map Title depending on what the search type, map type and nuber of properties are */
/*------------------------------------------------------------------------------------------------*/
    function MapTitle(SearchType, MapType, NoProps)
    {
        //NoProps + " properties matched (maximum 300 displayed) Locations are approximate to 200m.";
        var mapTitle = "";
        if(MapType == "single")
        {
            if(SearchType == "Branch")
            {
                mapTitle = "1 branch matched - Location is approximate to 200m.";
            }
            else
            {
                mapTitle = "1 property matched - Location is approximate to 200m.";
            }    
        }
        else
        {
            if(SearchType == "Branch")
            {
                if(NoProps != 1)
                {
                    mapTitle = NoProps + " branches matched - Locations are approximate to 200m.";   
                }
                else
                {
                    mapTitle = "1 branch matched - Location is approximate to 200m.";
                }
            }
            else
            {
                if(NoProps != 1)
                {
                    mapTitle = NoProps + " properties matched (maximum 300 displayed) Locations are approximate to 200m.";   
                }
                else
                {
                    mapTitle = "1 property matched - Location is approximate to 200m.";
                }
            }
        }
        return mapTitle;
    }

/*------------------------------------------------------------------------------------------------*/
/*  Creates And Returns An Icon.  Type Parameter Used To Specify Correct Image For Property Type  */
/*------------------------------------------------------------------------------------------------*/
	function CreateIcon(Type)
	{

	// Create our "tiny" marker icon
		var icon = new GIcon();
		var IconURL = document.getElementById('iconURL').value + "/images/Map/";
		icon.image = IconURL + Type + ".gif";
		//icon.shadow = "images/shadow.png";
		icon.iconSize = new GSize(16, 16);
		//icon.shadowSize = new GSize(0, 0);
		icon.iconAnchor = new GPoint(5, 1);
		icon.infoWindowAnchor = new GPoint(5, 1);
		return icon;
	}
	
/*------------------------------------------------------------------------------------------------*/
/* Creates A  Info Window @ LatLng "Point"												          */
/*------------------------------------------------------------------------------------------------*/  
    function CreatePropMarker(Point, infoTabs, icon, tooltip)
    {
    	/*Create Reference To marker*/
    	var marker = new GMarker(Point, { title: tooltip, icon: icon});
		
		/*Either Opens An Info Window If A Marker Is Clicked or Places A Marker @ Position*/
		GEvent.addListener(marker, "click", function() {
		
		    marker.openInfoWindowHtml("" + infoTabs);
		});
		
		arrPropMarkers[cnt] = marker;
		cnt++;
		
		/*Return Newly Created Marker*/
		return marker;	    
    }

/*------------------------------------------------------------------------------------------------*/
/* Creates A  tabbed Info Window @ LatLng "Point"												  */
/*------------------------------------------------------------------------------------------------*/  
     
      function CreateTabbedPropMarker(point,infoTabs,lables,icon,tooltip) 
      {
       	var marker = new GMarker(point, { title: tooltip, icon: icon});
       	
        GEvent.addListener(marker, "click", function() {
          // adjust the width so that the info window is large enough for this many tabs
          if (infoTabs.length > 4) {
            var multiplier = infoTabs.length;
            if(multiplier > 8) multiplier = 8;
            infoTabs[0] = '<div style="width:'+multiplier*88+'px">' + infoTabs[0] + '</div>';
          }
          var tabs = [];
          for (var i=0; i<infoTabs.length && i<8; i++) {
              tabs.push(new GInfoWindowTab(lables[i],infoTabs[i]));
          }
          marker.openInfoWindowTabsHtml(tabs);
        });
        return marker;
      }
      