
var map = null;
var results = 0;
var gh_markln = '';
var gh_count = 0;
var gh_count_str = 'Please narrow to less than 200 properties.';
var gh_homepage = '';
var gh_pins = new Object;
var gh_pinsNew = new Object;
var gh_openIW = '';
var gh_counting = 0;
var gh_searching = 0;
var gh_newCount = 0;
var gh_newSearch = 0;
var gh_logLastTime = new Date;
var gh_windowOpen = 0;
var gh_windowOpenClicked = 0;
var gh_lnWindowID = 0;
var lastLn = 0;
var mapCenterInitial = 0;
var ghLastOpenRow = new Array;
var ghHomeIcons = new Array;
var gh_DummyOverlay;
var gh_Projection;


// Start of ghBlankOverlay Object
function ghBlankOverlay(options) { 
	this.setValues(options);
	var div = this.div_ = document.createElement('div');
}

if (typeof google != 'undefined') {
	ghBlankOverlay.prototype = new google.maps.OverlayView();
}

ghBlankOverlay.prototype.onAdd = function() { 
	var pane = this.getPanes().overlayLayer;
	pane.appendChild(this.div_);
};

ghBlankOverlay.prototype.onRemove = function() { 
	this.div_.parentNode.removeChild(this.div_);
};

ghBlankOverlay.prototype.draw = function() { 
	gh_Projection = this.getProjection();

	var div = this.div_;
	div.style.display = 'none';
	if (mapCenterInitial == 0) {
		mapCenterInitial = gh_Projection.fromLatLngToDivPixel(map.getCenter());
	}
};
// End of Overlay Object


function thumbClick(thumbImg) {
	var tmp = $$("#gh_InfoWindow .ghInfoWindowThumbnail");
	var swap = tmp[0].src;
	tmp[0].src = thumbImg.src;
	thumbImg.src = swap;
}

function bubbledFromChild(element, event) {
  var target = event.element();
  if (target === element) target = event.relatedTarget;
  return (target && target.descendantOf(element));
}

function log(message) {
	return;

	var currentTime = new Date();
	var timePassed = currentTime - gh_logLastTime;
	gh_logLastTime = currentTime;
	var hours = currentTime.getHours();
	var minutes = currentTime.getMinutes();
	var seconds = currentTime.getSeconds();
	if (minutes < 10){
		minutes = "0" + minutes;
	}
	if (seconds < 10){
		seconds = "0" + seconds;
	}
    if (!log.window_ || log.window_.closed) {
        var win = window.open("", null, "width=400,height=200," +
                              "scrollbars=yes,resizable=yes,status=no," +
                              "location=no,menubar=no,toolbar=no");
        if (!win) return;
        var doc = win.document;
        doc.write("<html><head><title>Debug Log</title></head>" +
                  "<body></body></html>");
        doc.close();
        log.window_ = win;
    }
    var logLine = log.window_.document.createElement("div");
    logLine.appendChild(log.window_.document.createTextNode("["+timePassed+"]" + "(" + hours + ":" + minutes + ":" + seconds + ") "));
    logLine.appendChild(log.window_.document.createTextNode(message));
//    log.window_.document.body.appendChild(logLine);
    log.window_.document.body.insertBefore(logLine,log.window_.document.body.firstChild);
}

function msHover() {
	if (!document.getElementById("ms")) {
		return;
	}
    var msEls = document.getElementById("ms").getElementsByTagName("dd");
    for (var i=0; i<msEls.length; i++) {
        msEls[i].onmouseover=function() {
			this.originalClass = this.className;
            this.className ='mshover';
        }
        msEls[i].onmouseout=function() {
            this.className=this.className = this.originalClass;
        }
    }
}

function ghShowNewMapMarkers()
{
	log('Start: ghShowNewMapMarkers');

	for (var i in gh_pins)
	{
		if (!gh_pinsNew[i])
		{
			gh_pins[i].hide();
			delete gh_pins[i];
		}
		else
		{
			delete gh_pinsNew[i];
		}
	}
	for (var i in gh_pinsNew)
	{
		gh_pins[i] = gh_pinsNew[i];
		gh_pins[i].show();
	}
	gh_pinsNew = new Object();
	log('Done: ghShowNewMapMarkers');
}

function ghRowHover(ln)
{
	log('Start: ghRowHover');
	var ln = this.id.split('_')[0];
	ghHandleMarkerMouseOver(ln, gh_pins[ln].markerText, gh_pins[ln].pin);
	log('End: ghRowHover');
}

function ghRowHoverOff(ln)
{
	log('Start: ghRowHover');
	var ln = this.id.split('_')[0];
	ghHandleMarkerMouseOut(ln, gh_pins[ln].markerText, gh_pins[ln].pin);
	log('End: ghRowHover');
}

function ghRowClick(event)
{
	log('Start: ghRowClick');
	var ln = this.id.split('_')[0];
	ghHandleMarkerClick(ln, gh_pins[ln].markerText, gh_pins[ln].pin);
	log('End: ghRowClick');
}

function ghUpdateMarker(ln)
{
	log('Start: ghUpdateMarker');
	ghHandleMarkerClick(ln, gh_pins[ln].markerText, gh_pins[ln].pin);
	log('End: ghUpdateMarker');
}

function ghClearMapMarkers()
{
	log('Start: ghClearMapMarkers');

	for (var i in gh_pins)
	{
		gh_pins[i].hide();
	}
	gh_pins = new Object;
	gh_pinsNew = new Object;
	ghCloseInfoWindow();
	log('End: ghClearMapMarkers');
}

function ghOpenInfoWindow(ln, iwText, marker)
{
/*
	var intX = markerPoint.x - markerIcon.iconAnchor.x + markerIcon.infoWindowAnchor.x;
	var intY = markerPoint.y - markerIcon.iconAnchor.y + markerIcon.infoWindowAnchor.y;
	var mapWidth = map.getSize().width;
	var mapHeight = map.getSize().height;
*/
	log('Start: ghOpenInfoWindow');
	var markerIcon = marker.getIcon();
	var markerPoint = gh_Projection.fromLatLngToDivPixel(marker.getPosition());
	var mapPosition = $('map_canvas').viewportOffset();
	var mapX = mapPosition[0];
	var mapY = mapPosition[1];
	var mapCenterNew = gh_Projection.fromLatLngToDivPixel(map.getCenter());
	var offsetX = mapCenterInitial.x - mapCenterNew.x;
	var offsetY = mapCenterInitial.y - mapCenterNew.y;
	var scrolledOffset = document.viewport.getScrollOffsets();
	gh_lnWindowID = ln;
	$('gh_InfoWindow').innerHTML = iwText;
	$('gh_InfoWindow').setOpacity(1);
	$('gh_InfoWindow').style.left = (markerPoint.x + mapX - 60 + scrolledOffset[0] + offsetX) + 'px';
	$('gh_InfoWindow').style.top = (markerPoint.y + mapY - $('gh_InfoWindow').getHeight() - markerIcon.iconAnchor.y + scrolledOffset[1] + offsetY) + 'px';
	$('gh_InfoWindow').show();
	gh_windowOpen = 1;
	log('Done: ghOpenInfoWindow');
}

function ghCloseInfoWindow()
{
	gh_windowOpen = 0;
	gh_windowOpenClicked = 0;
	$('gh_InfoWindow').hide();
}

function ghHandleClickInfoWindow()
{
	var ln = gh_lnWindowID;
	ghHandleMarkerClick(ln, gh_pins[ln].markerText, gh_pins[ln].pin);
}

function ghHandleMarkerMouseOver(ln, iwText, marker)
{
	log('Start: mouseover');
	if (!gh_windowOpenClicked)
	{
		ghOpenInfoWindow(ln, iwText, marker);
	}
	gh_pins[ln].pin.setIcon(ghHomeIcons[gh_pins[ln].iconHover]);
	log('End: mouseover');
}

function ghHandleMarkerMouseOut(ln, iwText, marker)
{
	log('Start: mouseout');
	if (!gh_windowOpenClicked)
	{
		ghCloseInfoWindow();
	}
	gh_pins[ln].pin.setIcon(ghHomeIcons[gh_pins[ln].icon]);
	log('End: mouseout');
}

function ghHandleMarkerClick(ln, iwText, marker)
{
	log('Start: ghHandleMarkerClick');
	if (lastLn == ln && gh_windowOpen && !gh_windowOpenClicked)
	{
		gh_windowOpenClicked = 1;
	}
	else
	{
		ghHandleRowExpand(ln, iwText, marker);
	}
	log('Done: ghHandleMarkerClick');
}

function ghHandleRowExpand(ln, iwText, marker)
{
	log('Start: ghHandleRowExpand');
	if ($(ln+'_small').visible())
	{
		if (lastLn && $(lastLn+'_expand').visible())
		{
			hideMenu(lastLn+'_expand');
			toggleMenu(lastLn+'_small');
		}
		hideMenu(ln+'_small');
		toggleMenu(ln+'_expand');
		ghOpenInfoWindow(ln, iwText, marker);
		gh_windowOpenClicked = 1;
		lastLn = ln;
	}
	else
	{
		hideMenu(ln+'_expand');
		toggleMenu(ln+'_small');
		ghCloseInfoWindow();
		lastLn = 0;
	}
	log('Done: ghHandleRowExpand');
}

function ghPushPinControl(ln, lat, lng, iwText, oh)
{
	this.icon = (oh == "1") ? 'oh' : 'home';
	this.iconHover = (oh == "1") ? 'ohhover' : 'hover';
	this.markerLocation = new google.maps.LatLng(lat, lng);
	var marker = new google.maps.Marker({ 
		position: this.markerLocation, 
		title: 'MLS# ' + ln, 
		icon: ghHomeIcons[this.icon] 
	});
	this.pin = marker;
	this.ln = ln;
	this.lat = lat;
	this.lng = lng;
	this.markerText = iwText;
	google.maps.event.addListener(marker, "click", function() {
		ghHandleMarkerClick(ln,iwText,marker);
	});
	google.maps.event.addListener(marker, "mouseover", function() {
		ghHandleMarkerMouseOver(ln,iwText,marker);
	});
	google.maps.event.addListener(marker, "mouseout", function() {
		ghHandleMarkerMouseOut(ln,iwText,marker);
	});
}

ghPushPinControl.prototype.show = function() {
	this.pin.setMap(map);
	// map.addOverlay(this.pin);
}

ghPushPinControl.prototype.hide = function() {
	this.pin.setMap(null);
	// map.removeOverlay(this.pin);
}

function doneSearching()
{
	ghCloseInfoWindow();
	log('Start: doneSearching');
	gh_searching = 0;
	if (lastLn)
	{
		ghCloseInfoWindow();
		if ($(lastLn+'_expand').visible())
		{
			hideMenu(lastLn+'_expand');
			toggleMenu(lastLn+'_small');
		}
		ghLastOpenRow = new Array;
		lastLn = 0;
	}
	if (gh_newCount)
	{
		gh_newCount = 0;
		gh_newSearch = 0;
		updateCount();
	}
	else if (gh_newSearch)
	{
		gh_newSearch = 0;
		updateSearch();
	}
	else
	{
		getListingMarkers();
	}
	log('Done: doneSearching');
}

function getListingMarkers()
{
	log('Start: getListingMarkers');
	var allLns = document.getElementById("ms").getElementsByTagName("dd");
	for (var i=0; i<allLns.length; i++)
	{
		if (allLns[i].className == 'listingMarker')
		{
			var myln = allLns[i];
			if (myln.id && myln.getAttribute('lat'), myln.getAttribute('long'))
			{
				var iwText = $(myln.id+'_infowindow');
				if (!iwText)
				{
					iwText = 'MLS #: ' + myln.id;
				}
				else
				{
					iwText = iwText.innerHTML;
				}
				gh_pinsNew[myln.id] = new ghPushPinControl(myln.id, myln.getAttribute('lat'), myln.getAttribute('long'), iwText, myln.getAttribute('oh'));

				$(myln.id+'_small').observe('click',ghRowClick);
				$(myln.id+'_expand').observe('click',ghRowClick);
				$(myln.id+'_small').observe('mouseover',ghRowHover);
				$(myln.id+'_expand').observe('mouseover',ghRowHover);
				$(myln.id+'_small').observe('mouseout',ghRowHoverOff);
				$(myln.id+'_expand').observe('mouseout',ghRowHoverOff);
			}
		}
	}
	ghShowNewMapMarkers();
	log('Done: getListingMarkers');
}

function updateMapLocation()
{
	if (map.getBounds() == null) {
		alert('Bounds is null');
		ghCloseInfoWindow();
		lastLn = 0;
		if (gh_searching || gh_counting) {
			gh_newCount = 1;
		} else {
			$('gh_InfoWindow').setOpacity(.5);
			updateCount();
		}
		return;
	}
	var mapboundry = map.getBounds();
	var swbound = mapboundry.getSouthWest();
	var nebound = mapboundry.getNorthEast();
	var center = map.getCenter();
	var zoomlevel = map.getZoom();

	log("Updating map location");
	ghCloseInfoWindow();
	lastLn = 0;

	window.document.criteria.minlatitude.value = swbound.lat();
	window.document.criteria.minlongitude.value = swbound.lng();
	window.document.criteria.maxlatitude.value = nebound.lat();
	window.document.criteria.maxlongitude.value = nebound.lng();

	window.document.criteria.mclat.value = center.lat();
	window.document.criteria.mclng.value = center.lng();
	window.document.criteria.mczoom.value = zoomlevel;

	// for testing, only update search when clicking button
	if (gh_searching || gh_counting)
	{
		gh_newCount = 1;
	}
	else
	{
		$('gh_InfoWindow').setOpacity(.5);
		updateCount();
	}
}

function initialize(lat, lng, zoom) {
	var mylat = '44.574811';
	var mylng = '-123.262611';
	var myzoom = 4;

	if (lat) {
		mylat = lat;
	}
	if (lng) {
		mylng = lng;
	}
	if (zoom) {
		myzoom = zoom;
	}

//	$('gh_InfoWindow').observe('click',ghHandleClickInfoWindow);
	Event.observe(document.onresize ? document : window, "resize", function() {
		if(gh_windowOpen) {
			ghOpenInfoWindow(gh_lnWindowID, gh_pins[gh_lnWindowID].markerText, gh_pins[gh_lnWindowID].pin);
		}
	});
//	$('sp_mapsearch_section5').observe('mouseout',ghHandleMarkerMouseOut);

	var myOptions = {
		zoom: myzoom,
		center: new google.maps.LatLng(mylat, mylng),
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		mapTypeControl: true,
		mapTypeControlOptions: {
			style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
			position: google.maps.ControlPosition.TOP_RIGHT
		},
		navigationControl: true,
		navigationControlOptions: {
			style: google.maps.NavigationControlStyle.ZOOM_PAN,
			position: google.maps.ControlPosition.LEFT
		},
		scrollwheel: false
	};

	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

	gh_DummyOverlay = new ghBlankOverlay({ map: map });

	google.maps.event.addListener(map, "idle", function() {
		gh_DummyOverlay.setMap(null);
		gh_DummyOverlay = null;
		gh_DummyOverlay = new ghBlankOverlay({ map: map });
		updateMapLocation();
	});

	google.maps.event.addListener(map, "click", function(overlay, latlng) {
		if (!overlay) {
			ghCloseInfoWindow();
		}
	});

	google.maps.event.addListener(map, 'tilesloaded', function() {
		// only called once
		updateMapLocation();
		google.maps.event.clearListeners(map, 'tilesloaded');
	});

	ghHomeIcons['home'] = new google.maps.MarkerImage(
		'/common/in_images/map/pic_houseicon.png',
		new google.maps.Size(20,19),
		// Origin
		new google.maps.Point(0,0),
		// Anchor for this image
		new google.maps.Point(10,19)
	);
	ghHomeIcons['home'].iconAnchor = new google.maps.Point(10,19);
	ghHomeIcons['home'].infoWindowAnchor = new google.maps.Point(10,1);


	ghHomeIcons['hover'] = new google.maps.MarkerImage(
		'/common/in_images/map/pic_houseicon_on.png',
		new google.maps.Size(20,19),
		// Origin
		new google.maps.Point(0,0),
		// Anchor for this image
		new google.maps.Point(10,19)
	);
	ghHomeIcons['hover'].iconAnchor = new google.maps.Point(10,19);
	ghHomeIcons['hover'].infoWindowAnchor = new google.maps.Point(10,1);


	ghHomeIcons['oh'] = new google.maps.MarkerImage(
		'/common/in_images/map/pic_houseicon_oh.png',
		new google.maps.Size(22,38),
		// Origin
		new google.maps.Point(0,0),
		// Anchor for this image
		new google.maps.Point(11,38)
	);
	ghHomeIcons['oh'].iconAnchor = new google.maps.Point(11,38);
	ghHomeIcons['oh'].infoWindowAnchor = new google.maps.Point(11,1);


	ghHomeIcons['ohhover'] = new google.maps.MarkerImage(
		'/common/in_images/map/pic_houseicon_oh_on.png',
		new google.maps.Size(22,38),
		// Origin
		new google.maps.Point(0,0),
		// Anchor for this image
		new google.maps.Point(11,38)
	);
	ghHomeIcons['ohhover'].iconAnchor = new google.maps.Point(11,38);
	ghHomeIcons['ohhover'].infoWindowAnchor = new google.maps.Point(11,1);

}

function updateSearchStatus(statusText)
{
	if (Prototype.Browser.IE)
	{
		return;
	}
	log('Start: updateSearchStatus');
	if ($('gh_pagestatus') && statusText)
	{
		log('Update: updateSearchStatus (dim results) -- ' + statusText);
		$('gh_pagestatus').innerHTML = statusText;
		$('ms').setOpacity(.5);
	}
	else
	{
		log('Update: updateSearchStatus');
		$('sp_mapsearch_section5').innerHTML = statusText;
	}
	log('Done: updateSearchStatus');
}

function gh_doSearch()
{
	log('Start: gh_doSearch');
	updateSearchStatus('Updating Results, Please Wait ...');
	Ajax.Responders.register({
		onComplete: function(){
			msHover();
		}
	});

	new Ajax.Updater('sp_mapsearch_section5', gh_homepage + '/cgi-bin/aa.fcgi',
	{
		parameters: $('mapform').serialize(true),
		method:'get',
		onComplete: doneSearching
	});
	log('Done: gh_doSearch');
}

function updateSearch()
{
	log('Start: updateSearch');
	if (gh_searching || gh_counting)
	{
		gh_newSearch = 1;
		log('Skip: updateSearch');
		return;
	}
	// if trying to save pw's & count = 0, then clear 'sp_mapsearch_section5' when done ...
	if ((gh_count > 200) || (gh_count < 1)) {
		if ($('mapform')['prospector'].value == '1') {
			// Save Search & clear results
			new Ajax.Request(gh_homepage + '/cgi-bin/aa.fcgi',
			{
				parameters: $('mapform').serialize(true),
				method:'get',
				onComplete: function(transport) {
					$('sp_mapsearch_section5').innerHTML = '';
					window.document.criteria.prospector.value = '0';
				}
			});
		} else {
			$('sp_mapsearch_section5').innerHTML = '';
		}
		ghClearMapMarkers();
	} else {
		gh_searching = 1;
		gh_newSearch = 0;
		gh_doSearch();
	}
	log('Done: updateSearch');
}

function updateSearchBy(orderby)
{
	if ($('mapform')['o'].value == orderby + 'D') {
		$('mapform')['o'].value = orderby;
	} else {
		$('mapform')['o'].value = orderby + 'D';
	}
	if (gh_counting || gh_searching)
	{
		gh_newSearch = 1;
	}
	else
	{
		updateSearch();
	}
}

function doneCounting()
{
	gh_counting = 0;
	if (gh_newCount)
	{
		gh_newCount = 0;
		gh_newSearch = 0;
		updateCount();
	}
	else
	{
		updateSearch();
	}
}

function updateCount()
{
	log('Start: updateCount');
	if (gh_searching || gh_counting)
	{
		gh_newCount = 1;
		log('Skip: updateCount');
		return;
	}
	gh_counting = 1;
	window.document.criteria.count.value = 1;
	new Ajax.Request(gh_homepage + '/cgi-bin/aa.fcgi',
	{
		parameters: $('mapform').serialize(true),
		method:'get',
		onComplete: function(transport) {
			var n;

			n = transport.responseText;
			if (n != parseInt(n)) {
				gh_count = 0;
				gh_count_str = 'Server unable to respond.';
			} else {
				gh_count = n;
				gh_count_str = '';
				if (n < 1) {
					gh_count_str = 'Please refine your search.';
					$('gh_MapInstructionsBubble').hide();
				}
				else if (n > 200) {
					gh_count_str = 'Please narrow to less than 200 properties.';
					$('gh_MapInstructionsBubble').show();
				} else {
					$('gh_MapInstructionsBubble').hide();
				}

			}
			$('ms_numberfound').innerHTML = gh_count + ' Properties Found.';
			$('ms_errorfound').innerHTML = gh_count_str + ' &nbsp; ';
			window.document.criteria.count.value = '';
			doneCounting();
		},
		onFailure: function(transport) {
			log('failed');
		}
	});
	window.document.criteria.count.value = '';
	log('Done: updateCount');
}

function changeSelectPropType(psearch, sosubtype)
{
	var obj = window.document.criteria.proptype.options;
	var name = psearch;

	if ((sosubtype) && (sosubtype == '1')) {
		name = '1-1';
	}
	for(i=0; i<obj.length; i++) {
		if (obj[i].value.toLowerCase() == name.toLowerCase()) {
			obj[i].selected = true;
		} else {
			obj[i].selected = false;
		}
	}
}

function updateCriteriaForm(psearch, sosubtype, id)
{
	var myparms = {
		go: 'so',
		l:  '3',
		st: '2',
		tab: 'map'
	};
	myparms.psearch = psearch;
	if (sosubtype != 0) {
		myparms.sosubtype = sosubtype;
	}
	new Ajax.Request(gh_homepage + '/cgi-bin/aa.fcgi',
	{
		parameters: myparms,
		method:'get',
		onComplete: function(transport) {
			$('ms_mapcriteria_section').innerHTML = transport.responseText;
			changeSelectPropType(psearch, sosubtype);
			updateMapLocation();
		}
	});
}

function changeMapSearchPropType(psearch, id)
{
	if (psearch == '1-1') {
		if (id) {
			updateCriteriaForm(1, 1, id);
		} else {
			updateCriteriaForm(1, 1);
		}
	} else {
		if (id) {
			updateCriteriaForm(psearch, 0, id);
		} else {
			updateCriteriaForm(psearch, 0);
		}
	}
}

function changeResultsPage(url)
{
	updateSearchStatus('Updating Results, Please Wait ...');
	Ajax.Responders.register({
		onComplete: function(){
			msHover();
		}
	});

	ghCloseInfoWindow();
	lastLn = 0;
    if (url.charAt(0) == '/') {
        url = gh_homepage + url;
    }
	new Ajax.Updater('sp_mapsearch_section5', url,
	{
		method:'get',
		onComplete: doneSearching
	});
}

