//this are values that need to be intialized by main search script
var _search = null; //search.js
var _saved_search = null; //saved_search.js
var _mdc = null; //map.js MapOwner
var _infowindow = false;
var cur_home_lng = 0;
var cur_home_lat = 0;
(function () 
{
    google.maps.Map.prototype.markers = new Array();
    
    google.maps.Map.prototype.addMarker = function(marker) 
    {
        this.markers[this.markers.length] = marker;
    };
    
    google.maps.Map.prototype.getMarkers = function() 
    {
        return this.markers
    };
    
    google.maps.Map.prototype.clearMarkers = function() 
    {
        if(_infowindow) 
        {
            infowindow.close();
        }
    
        for(var i=0; i<this.markers.length; i++)
        {
            this.markers[i].setMap(null);
        }
        this.markers = new Array();
    };
})();

function tooltip_overlay(map)
{
    this.div = null;
    this.map = map;
    this.setMap(map);
}
tooltip_overlay.prototype = new google.maps.OverlayView();

tooltip_overlay.prototype.onAdd = function()
{
    this.div = $('home_tooltip');
    $('map').appendChild(this.div);
//    var panes = this.getPanes();
//    panes.floatPane.appendChild(this.div);
}

tooltip_overlay.prototype.onRemove = function()
{

}

tooltip_overlay.prototype.draw = function()
{
    var bounds = _mdc.map.getBounds();
    if (typeof(bounds) ==  'undefined')
    {
        return;
    }
    var point = this.getProjection().fromLatLngToDivPixel(bounds.getSouthWest());
    var point2 = this.getProjection().fromLatLngToDivPixel(bounds.getNorthEast());
    if (_mdc.tooltip_marker == null)
    {
        return;
    }
    
    var markerpos = _mdc.tooltip_marker.getPosition();
    var lat = markerpos.lat();
    var lng = markerpos.lng();
    var latlng = new google.maps.LatLng(lat*1, lng*1);
    var offset = this.getProjection().fromLatLngToDivPixel(markerpos);
    
//    var x = point.x-offset.x + 4;
    var x = offset.x - _mdc.tipWidth-10 - point.x;
//    var y = offset.y - point.y -_mdc.tipHeight-11;
    var y = offset.y - _mdc.tipHeight-11 - point2.y;
//    var pos = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(x, y)); 
    
    this.div.style.top = y+'px';
    this.div.style.left = x+'px';
    
//    pos.apply(_mdc.tooltip);
    _mdc.tooltip.style.display = "block";
    $('map').style.overflow = "";

}
var MapDisplayController = Class.create();

MapDisplayController.prototype = 
{
	initialize: function(web_template_path)
	{
		this.currentZoom = -1;
		this.prevViewType = "street";
		this.web_template_path = web_template_path;
		
		//house icons
        this.iHomeSale = new google.maps.MarkerImage(
            this.web_template_path+"/images/map/map_icon.php",
            new google.maps.Size(22, 22),
            new google.maps.Point(0,0),
            new google.maps.Point(6, 17));

        this.iHomeSaleOpenHouse = new google.maps.MarkerImage(
            this.web_template_path+"/images/map/map_icon.php?type=openhouse",
            new google.maps.Size(26, 26), 
            new google.maps.Point(0,0),
            new google.maps.Point(6, 17));

        this.iHomeSaleOpenHouseSel = new google.maps.MarkerImage(
            this.web_template_path+"/images/map/map_icon.php?type=openhouse_sel",
            new google.maps.Size(26, 26), 
            new google.maps.Point(0,0),
            new google.maps.Point(6, 17));

        this.iHomeSaleMine = new google.maps.MarkerImage(
            this.web_template_path+"/images/map/map_icon.php?type=mine",
            new google.maps.Size(31, 31), 
            new google.maps.Point(0,0),
            new google.maps.Point(6, 17));

        this.iHomeSaleMineSel = new google.maps.MarkerImage(
            this.web_template_path+"/images/map/map_icon.php?type=mine_sel",
            new google.maps.Size(31, 31), 
            new google.maps.Point(0,0),
            new google.maps.Point(6, 17));

        this.iHomeSaleSel = new google.maps.MarkerImage(
            this.web_template_path+"/images/map/map_icon.php?type=sel",
            new google.maps.Size(22, 22), 
            new google.maps.Point(0,0),
            new google.maps.Point(6, 17));

        this.iHomeSaleComp = new google.maps.MarkerImage(
            this.web_template_path+"/images/map/map_icon.php?type=comp",
            new google.maps.Size(22, 22), 
            new google.maps.Point(0,0),
            new google.maps.Point(6, 17));

        this.iFSBO = this.iHomeSale;
        this.iFSBOAgent = this.iHomeSale;
        this.iFSBOSel = this.iHomeSaleSel;
        this.iFSBOComp = this.iHomeSaleComp;


		//global variables for all js files
        var latlng = new google.maps.LatLng(-34.397, 150.644);
        var mapOptions = 
        {
            zoom: 8,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableDefaultUI: false,
            zoomControl: false,
            mapTypeControl: false
        };

		this.mapDiv = $('map');
		this.map = new google.maps.Map(this.mapDiv, mapOptions);
//		this.map.addControl(new GOverviewMapControl());
		thismap = this.map;
        this.tilesLoaded = google.maps.event.addListener(this.map, 'tilesloaded', mapLoadedEvent);
        google.maps.event.addListener(this.map, 'zoom_changed', function () {
        	var thecurzoomlevel = thismap.getZoom();
        	_mdc.currentZoom = thecurzoomlevel;
        	_mdc.updateZoomBar();
        	_mdc.zoomMap(thecurzoomlevel);
        	/*for(var i = 3; i <= 17; i++) {
        		if(i<=thecurzoomlevel) {
        			document.getElementById("zoom_"+i).className = "borange";
        		} else {
        			document.getElementById("zoom_"+i).className = "bgrey";
        		}
        	}*/
        });

        this.home_tooltip = new tooltip_overlay(this.map);

   		this.tooltip = null;
		this.tooltip = $('home_tooltip');
		this.tooltip.id = 'home_tooltip';
		
		this.mapHomes = new Array();
		this.mapHomesCount = 0;
		this.currentHome = null;
		
		this.selectedZoomColor = 'borange';
		this.deselectedZoomColor = 'bgrey';
		
        initTabs(this.web_template_path);
	},
	checkGoogleZoom:function (thismap) {
		var thecurzoomLevel = thismap.getZoom();
		//alert("Zoom: "+thismap.getZoom());
	},
	clearHomes:function()
	{
		this.map.clearMarkers();
		//clear homes
		var size = this.mapHomes.length;
		for(var i = 0; i < size; i++)
		{
			if(this.mapHomes[i] != null)
			{
				delete this.mapHomes[i];
			}
			
			this.mapHomes[i] = null;
		}
		this.mapHomes = new Array();
		this.mapHomesCount = 0;
		this.currentHome = null;
		
	},
	zoomMap:function(level)
	{
		if(level == this.currentZoom)return;
		
		this.currentZoom = level;
		this.updateZoomBar();
		this.map.setZoom(level);
	},
	updateZoomBar:function()
	{
		for(var i = 3; i <= 17; i++)
		{
			if(i >= this.currentZoom)
			{
				$('zoom_' + i).className = this.selectedZoomColor;
			}
			else
			{
				$('zoom_' + i).className = this.deselectedZoomColor;
			}
		}
	},
	zoomIn:function()
	{
		if(this.currentZoom == 17) return;
		
		this.zoomMap(this.currentZoom+1);
	},
	zoomOut:function()
	{
		if(this.currentZoom == 3) return;
		
		this.zoomMap(this.currentZoom-1);
	},
	changeMapType:function(type)
	{
		if(this.prevViewType == type)
		{
			return;
		}
		
		$(this.prevViewType + "_text").className = "cblack map_view";

		$(this.prevViewType + "_lt").className = "";
		$(this.prevViewType + "_rt").className = "";
		
		$(type + "_text").className = "cwhite borange map_view";
		$(type + "_lt").className = "borange";
		$(type + "_rt").className = "borange";
		
		if(type == "street")
		{
			this.map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
		}
		else if(type == "satellite")
		{
			this.map.setMapTypeId(google.maps.MapTypeId.SATELLITE);
		}
        else
		{	
			this.map.setMapTypeId(google.maps.MapTypeId.HYBRID);
		}
		
		this.prevViewType = type;
	},
	sortHomes:function(h1, h2)
	{
		if((+h1.id) < (+h2.id))
		{
			return -1;
		}
		else if((+h1.id) > (+h2.id))
		{
			return 1;
		}
		
		return 0;
	},
	findHomeById:function(id)
	{
		var size = this.mapHomes.length;
		if(size == 0)
		{
			return null;
		}
		
		if(this.mapHomes[0].id == id)
		{
			return this.mapHomes[0];
		}
		
		if(size == 1)
		{
			return null;
		}
		
		if(this.mapHomes[size-1].id == id)
		{
			return this.mapHomes[size-1];
		}
		
		//did end cases now binary search
		var lt = 0;
		var md = 0;
		var rt = size-1;
		
		while(lt <= rt)
		{
			md = parseInt((lt + rt)/2, 10);
			if(this.mapHomes[md].id == id)
			{
				return this.mapHomes[md];
			}
			else if((+this.mapHomes[md].id) < (+id))
			{
				lt = md+1;
			}
			else if((+this.mapHomes[md].id) > (+id))
			{
				rt = md-1;
			}
		}
		
		//see if it is in the comps section
		if(this.mapHomes.length > this.mapHomesCount)
		{
			for(var i = this.mapHomesCount; i < this.mapHomes.length; i++)
			{
				if(this.mapHomes[i].id == id)
				{
					return this.mapHomes[i];
				}
			}
		}
		
		return null;
	},
	findFirstHome:function()
	{
		if(this.mapHomes.length == 0)
		{
			return null;
		}
		
		return this.mapHomes[0];
	},
	hideDisclaimers:function()
	{
		//bch36: corrected "diclaimer" to "disclaimer"
		var td = $('disclaimer_table');
		if (!td)
			return;
		
		var ds = td.getElementsByTagName("div");
		
		for(var i = 0; i < ds.length; i++)
		{
			ds[i].style.display = "none";
		}
	},

    blueroofControls: function()
    {
        this.updateZoomBar = this.blueroofUpdateZoomBar;
        this.changeMapType = this.blueroofChangeMapType;
        this.iHomeSale = new google.maps.MarkerImage(
            this.web_template_path+"/images/map/br_for_sale.gif",
            new google.maps.Size(30, 22), 
            new google.maps.Point(0,0),
            new google.maps.Point(6, 17));

        this.iHomeSaleMine = new google.maps.MarkerImage(
            this.web_template_path+"/images/map/br_blueroof_home.png",
            new google.maps.Size(33, 33), 
            new google.maps.Point(0,0),
            new google.maps.Point(6, 17));

        this.iHomeSaleMineSel = new google.maps.MarkerImage(
            this.web_template_path+"/images/map/br_for_sale_sel.gif",
            new google.maps.Size(33, 33), 
            new google.maps.Point(0,0),
            new google.maps.Point(6, 17));

        this.iHomeSaleSel = new google.maps.MarkerImage(
            this.web_template_path+"/images/map/br_for_sale_sel.gif",
            new google.maps.Size(33, 33), 
            new google.maps.Point(0,0),
            new google.maps.Point(6, 17));

        this.iHomeSaleComp = new google.maps.MarkerImage(
            this.web_template_path+"/images/map/br_for_sale_comp.gif",
            new google.maps.Size(33, 33), 
            new google.maps.Point(0,0),
            new google.maps.Point(6, 17));

        this.iFSBO = new google.maps.MarkerImage(
            this.web_template_path+"/images/map/br_fsbo.gif",
            new google.maps.Size(30, 22), 
            new google.maps.Point(0,0),
            new google.maps.Point(6, 17));

        this.iFSBOAgent = new google.maps.MarkerImage(
            this.web_template_path+"/images/map/br_fsbo_agent.gif",
            new google.maps.Size(30, 22), 
            new google.maps.Point(0,0),
            new google.maps.Point(6, 17));

        this.iFSBOSel = this.iHomeSaleSel;
        this.iFSBOComp = this.iHomeSaleComp;
		
    },

    blueroofUpdateZoomBar: function()
    {
		for(var i = 3; i <= 17; i++)
		{
			if(i == this.currentZoom && $('zoom_img_' + i))
			{
				$('zoom_img_' + i).src = "/shared/images/zoom_tick_selected.gif";
			}
			else if ($('zoom_img_' + i))
			{
				$('zoom_img_' + i).src = "/shared/images/zoom_tick.gif";
			}
		}
    },
    blueroofChangeMapType: function(type)
	{
		/*if(this.prevViewType == type && type != "street_view") {
			return;
		}*/
		
		if(this.prevViewType != type) {
			$(this.prevViewType + "_text").className = "map_type_unselected map_type";
			$(type + "_text").className = "map_type_selected map_type";
		}
		
        /*if (this.prevViewType == "street_view")
        {
            this.map.removeOverlay(this.street_view);
            $('sv_div').style.display='none';
        }*/

      
		if(type == "street")
		{
			this.map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
		}
		else if(type == "satellite")
		{
			this.map.setMapTypeId(google.maps.MapTypeId.SATELLITE);
		}
        else if (type=="hybrid")
		{	
			this.map.setMapTypeId(google.maps.MapTypeId.HYBRID);
		}
		else if (type=="street_view")
		{
			if(cur_home_lng==0 && cur_home_lat==0) {
				alert("Could not find a home for street view");
			} else {
				//this.map.setMapTypeId(google.maps.MapTypeId.TERRAIN);
				var curPlace = new google.maps.LatLng(cur_home_lat, cur_home_lng);
				var panorama = this.map.getStreetView();
				panorama.setVisible(false);
			    panorama.setPosition(curPlace);
			    /*panorama.setPov({
			      heading: 265,
			      zoom:1,
			      pitch:0}
			    );*/
			    panorama.setVisible(true);
			}
		}
        /*else
        {
            this.map.setMapType(G_NORMAL_MAP);
            if (this.street_view == null)
            {
                this.street_view = new GStreetviewOverlay();
            }
            this.map.addOverlay(this.street_view);
        }*/
		
		this.prevViewType = type;
    },
    
    
    checkStreetView: function(overlay, latlng, overlaylatlng)
    {
        if (overlay != null)
        {
            if (overlay == this.street_view)
            {
                $('sv_div').style.display = 'block';
                /* start a street view here */
                this.sv_pan = new GStreetviewPanorama($('sv_div'));
                this.sv_pan.setLocationAndPOV(latlng);
            }
            else
            {
                $('sv_div').style.display = 'block';
                this.sv_pan.setLocationAndPOV(overlaylatlng);
            }
        }
    }

    
} //MapDisplayController

//tab controls
var lt_off_img = new Image();
var lt_on_img = new Image();
var rt_off_img = new Image();
var rt_on_img = new Image();
var on_off_img = new Image();
var off_on_img = new Image();
var off_off_img = new Image();
var bg_on_img = new Image();
var bg_off_img = new Image();

function initTabs(web_template_path)
{
	lt_off_img.src = web_template_path+"/images/map/tab_lt_off.png";
	lt_on_img.src = web_template_path+"/images/map/tab_lt_on.png";
	rt_off_img.src = web_template_path+"/images/map/tab_rt_off.png";
	rt_on_img.src = web_template_path+"/images/map/tab_rt_on.png";
	on_off_img.src = web_template_path+"/images/map/tab_on_off.png";
	off_on_img.src = web_template_path+"/images/map/tab_off_on.png";
	off_off_img.src = web_template_path+"/images/map/tab_off_off.png";
	bg_on_img.src = web_template_path+"/images/map/tab_bg_on.png";
	bg_off_img.src = web_template_path+"/images/map/tab_bg_off.png";
}

var currentTab = "search";
var currentNeighbor = "results";
function switchTab(tab, neighbor)
{
    if ($('search_lt') == null)
    {
        return(switchTab2(tab, neighbor));
    }
	$(currentTab + "_panel").style.display = "none";
	$('no_home_panel').style.display = "none";
    $('save_search_panel').style.display = "none";
	
	if(_mdc.currentHome || tab == "search" || (tab == "results" && _search.homeQuery != null))
	{
		$(tab + "_panel").style.display = "block";
	}
	else
	{
		if(tab == "results")
		{
			$('no_home_text').innerHTML = "no search performed";
		}
		else
		{
			$('no_home_text').innerHTML = "no home selected";
		}
		$('no_home_panel').style.display = "block";
	}
	
	
	lt_img = $(currentTab + "_lt");
	$(currentTab + "_text").className = "cwhite tab_off png";
	$(currentTab + "_text").style.backgroundImage = "";
	
	
	if(currentTab == "search")
	{
		$('search_lt').src = lt_off_img.src;
		$('results_lt').src = off_off_img.src;
	}
	else if(currentTab == "info")                                                   
	{                    
		$('info_lt').src = off_off_img.src;
		$("info_rt").src = rt_off_img.src;
	}
	else
	{
		$(currentTab + '_lt').src = off_off_img.src;
		$(currentNeighbor + '_lt').src = off_off_img.src;
	}
	
	$(tab + "_lt").src = off_on_img.src;
	$(tab + "_text").className = "cwhite tab_on png";
	$(tab + "_text").style.backgroundImage = "";
	
	if(tab == "search")
	{
		$("search_lt").src = lt_on_img.src;
		$("results_lt").src = on_off_img.src;
	}
	else if(tab == "results")
	{
		$("results_lt").src = off_on_img.src; 
		$("info_lt").src = on_off_img.src;
	}
	else if(tab == "info")
	{
		$("info_lt").src = off_on_img.src;
		$("info_rt").src = rt_on_img.src;
		
		if(_mdc.currentHome)
		{
			_mdc.currentHome.info.showInfo();
		}
		
	}
	
	currentTab = tab;
	currentNeighbor = neighbor;
}

function switchTab2(tab, neighbor)
{
/*    if (currentTab == 'search')
    {
        $('search_panel_view').style.display='none';
        $('search_tabs').style.display='block';
    }
    if (tab == 'search')
    {
        $('search_tabs').style.display='none';
	$('search_panel_view').style.display='block';
    }
*/
	if (typeof search_form_require_login != "undefined" && search_form_require_login == 'home_details' && tab == 'info')
	{
		if (!isUserLoggedIn())
		{
			requiredLogin("switchTab2('info','results');");
			return;
		}
        }
	$(currentTab + "_panel").style.display = "none";
	$('no_home_panel').style.display = "none";
    $('save_search_panel').style.display = "none";
	
	if(_mdc.currentHome || tab == "search" || (tab == "results" && _search.homeQuery != null))
	{
		$(tab + "_panel").style.display = "block";
	}
	else
	{
		if(tab == "results")
		{
			$('no_home_text').innerHTML = "no search performed";
		}
		else
		{
			$('no_home_text').innerHTML = "no home selected";
		}
		$('no_home_panel').style.display = "block";
	}
	
	
    $(currentTab+"_tab").className = "search_tab_off";
    $(tab+"_tab").className = "search_tab_on";

    if(_mdc.currentHome)
    {
    	if(tab == "info")
    	{
    	    _mdc.currentHome.info.showInfo();
		}
		
        if (tab == "comp")
        {
            _mdc.currentHome.info.showComps();
        }
        else
        {
            _mdc.currentHome.info.hideCompIcons();
        }
	}
	
	currentTab = tab;
	currentNeighbor = neighbor;
}

var MapBounds = Class.create();

MapBounds.prototype = 
{
    initialize : function(latlng)
    {
        this.minLat = this.maxLat = latlng.lat();
        this.minLng = this.maxLng = latlng.lng();
    },

    extend : function(latlng)
    {
        var lat = latlng.lat();
        var lng = latlng.lng();
        this.minLat = min(this.minLat, lat);
        this.minLng = min(this.minLng, lng);
        this.maxLat = max(this.maxLat, lat);
        this.maxLng = max(this.maxLng, lng);
    },

    centerLat : function(skew)
    {
        return(this.maxLat-((this.maxLat-this.minLat)*skew));
    },

    centerLng : function()
    {
        return((this.minLng+this.maxLng)/2);
    }
}


