// ####################################################################

var GM_MAP                = null;
var GM_PANO               = null;
var GM_BOUNDS             = null;
var GM_MARKERS            = new Array();
var GM_INFOWINDOWS        = new Array();
var GM_STREETVIEW_SERVICE = new google.maps.StreetViewService();
var GM_BOUNDS;//            = new google.maps.LatLngBounds();
var GM_ZOOMED             = false;
var SEARCH_FIELDS         = new Array(
	'category', 
	'builder', 
	'price', 
	'bed', 
	'bath', 
	'sqft',
	'area',
	'school_district'
);

function GM_Empty(bShow){
	if(bShow == true){
		jQuery('.gm_wait').hide();
		jQuery('.gm_empty').show();
	}else{
		jQuery('.gm_empty').hide();
	}
}

function GM_Wait(bShow){
	if(bShow == true){
		jQuery('.gm_empty').hide();
		jQuery('.gm_wait').show();
		GM_FormDisable();
	}else{
		jQuery('.gm_wait').hide();
		GM_FormEnable();
	}
}

function GM_FormEnable(){
	if(document.getElementById('featured')){
		document.getElementById('featured').disabled = false;
	}
	if(document.getElementById('open_house')){
		document.getElementById('open_house').disabled = false;
	}
	for(var index = 0; index < SEARCH_FIELDS.length; index++){
		if(document.getElementById(SEARCH_FIELDS[index])){
			document.getElementById(SEARCH_FIELDS[index]).disabled = false;
		}
	}
}

function GM_FormDisable(){
	if(document.getElementById('featured')){
		document.getElementById('featured').disabled = true;
	}
	if(document.getElementById('open_house')){
		document.getElementById('open_house').disabled = true;
	}
	for(var index = 0; index < SEARCH_FIELDS.length; index++){
		if(document.getElementById(SEARCH_FIELDS[index])){
			document.getElementById(SEARCH_FIELDS[index]).disabled = true;
		}
	}
}

function GM_Autoload(){
	Search_Category_Change();
}

function GM_Init(){
	var latlng    = new google.maps.LatLng(37.6814, -97.3435);
	var myOptions = {
		zoom: 8,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	GM_MAP    = new google.maps.Map(document.getElementById("gm_map"), myOptions);
	GM_BOUNDS = new google.maps.LatLngBounds();
	GM_MAP.enableKeyDragZoom();
	google.maps.event.addListener(GM_MAP.getDragZoomObject(), 'dragend', function(bnds){
		GM_BOUNDS = bnds;
		Search_LatLng_Change();
	});
	google.maps.event.addListener(GM_MAP, 'click', function(event){
		GM_InfoWindows_Close();
		GM_Pano_Delete();
	});
	jQuery(document).ready(function(){
		GM_Wait(true);
	});
}

function GM_Marker_Add(listing, latlng, map){
	if(GM_MAP){
		var marker = new google.maps.Marker({
			title    : listing.listing_title,
			position : latlng,
			map      : map
		});
		GM_BOUNDS.extend(latlng);
		GM_MAP.fitBounds(GM_BOUNDS);
		GM_MARKERS.push(marker);
		Search_AddMarkerLink(listing, marker);
		return marker;
	}
}

function GM_Marker_Delete(index){
	if(GM_MARKERS && typeof GM_MARKERS[index] != 'undefined'){
		GM_MARKERS[index].setMap(null);
		GM_MARKERS.splice(index, 1);
	}
}

function GM_Markers_Delete(){
	if(GM_MARKERS){
		for(var index = GM_MARKERS.length-1; index >= 0; index--){
			GM_Marker_Delete(index);
		}
	}
	if(document.getElementById('gm_markers')){
		document.getElementById('gm_markers').innerHTML = '';
	}
	if(document.getElementById('gm_results')){
		document.getElementById('gm_results').innerHTML = '';
	}
}

function GM_InfoWindow_Add(str){
	var infowindow = new google.maps.InfoWindow({
		content : str,
		width   : 240
	});
	GM_INFOWINDOWS.push(infowindow);
	return infowindow;
}

function GM_InfoWindow_Delete(index){
	if(GM_INFOWINDOWS && typeof GM_INFOWINDOWS[index] != 'undefined'){
		GM_INFOWINDOWS[index].setMap(null);
		GM_INFOWINDOWS.splice(index, 1);
	}
}

function GM_InfoWindows_Delete(){
	if(GM_INFOWINDOWS){
		for(var index = GM_INFOWINDOWS.length-1; index >= 0; index--){
			GM_InfoWindow_Delete(index);
		}
	}
}

function GM_InfoWindows_Close(){
	if(GM_INFOWINDOWS){
		for(var index = GM_INFOWINDOWS.length-1; index >= 0; index--){
			GM_INFOWINDOWS[index].close();
		}
	}
}

function GM_Pano_Delete(){
	if(GM_PANO != null){
		GM_PANO.unbind("position");
		GM_PANO.setVisible(false);
		GM_PANO = null;
	}
}

function GM_ItemAdd(listing){
	if(GM_MAP){
		// latlng
		var latlng = new google.maps.LatLng(listing.listing_latitude, listing.listing_longitude);
		// marker
		var marker = GM_Marker_Add(listing, latlng, GM_MAP);
		// infowindow content
		var html   = '<div class="infowindow_outer">';
		html      += '<div class="infowindow_left">';
		html      += '<b><a style="color:#333;" href="' + Search_GetListingLink(listing) + '">' + (listing.listing_title.length > 23 ? listing.listing_title.substring(0, 20) + '...' : listing.listing_title) + '</a></b><br/>';
		html      += listing.listing_addr1 + ' ' + listing.listing_addr2 + '<br/>';
		html      += listing.listing_city + ' ' + listing.listing_state + ' ' + listing.listing_zip;
		html      += '</div>';
	//	if(listing.listing_image){
	//		html += '<div class="infowindow_right">';
	//		html += '<a id="gm_show_thumb" href="javascript:;" onclick="GM_ShowThumb();">Image</a>' + (! navigator.userAgent.match(/safari/i) ? ' <span id="gm_sep">|</span> <a id="gm_show_streetview" href="javascript:;" onclick="GM_ShowStreetview();">Street</a>' : '');
	//		html += '</div>';
	//	}
		html += '<div class="clear">&nbsp;</div>';
		if(listing.listing_image){
			html += '<div style="display:block;" class="infowindow_image" id="GM_thumb"><img src="/image2.php?type=listing&id=' + listing.listing_id + '&file=' + listing.listing_image + '&size=mid&banner=1" alt="listing.listing_title"/></a></div>';
		}
	//	if(! navigator.userAgent.match(/safari/i)){ // don't show streetview in Safari
	//		html += '<div id="gm_pano" class="infowindow_pano"></div>';
	//	}
		html += '</div>';
		// infowindow
		var infwin = GM_InfoWindow_Add(html);
		google.maps.event.addListener(marker, 'click', function(){
			// close any open infowindows
			GM_InfoWindows_Close();
			// open current infowindow
			infwin.open(GM_MAP, marker);
/*
 			if(! navigator.userAgent.match(/safari/i)){ // don't show streetview in Safari
				// streetview (pano)
				google.maps.event.addListener(infwin, 'domready', function(){
					if(GM_PANO != null){
						GM_Pano_Delete();
					}
					GM_PANO = new google.maps.StreetViewPanorama(document.getElementById("gm_pano"), {
						navigationControl        : true,
						navigationControlOptions : {style : google.maps.NavigationControlStyle.SMALL},
						enableCloseButton        : false,
						addressControl           : false,
						linksControl             : false
					});
					if(GM_PANO != null){
						GM_STREETVIEW_SERVICE.getPanoramaByLocation(
							latlng, 
							50, 
							function(data, status){
								if(status == google.maps.StreetViewStatus.OK){
									GM_PANO.setPano(data.location.pano);
									GM_PANO.setVisible(true);
								}else{
									if(document.getElementById('gm_pano')){
										document.getElementById("gm_pano").style.height  = '1px';
									}
									GM_PANO.setVisible(false);
									GM_HideStreetviewLink();
									GM_ShowThumb();
								}
							}
						);
					}
				});
				google.maps.event.addListener(infwin, 'closeclick', function(){
					GM_Pano_Delete();
				});
			}
*/
		});
		return marker;
	}
}

function GM_ShowStreetview(){
	if(document.getElementById('GM_thumb')){
		document.getElementById('GM_thumb').style.display = 'none';
	}
	if(document.getElementById('gm_pano')){
		document.getElementById('gm_pano').style.display = 'block';
	}
}

function GM_ShowThumb(){
	if(document.getElementById('gm_pano')){
		document.getElementById('gm_pano').style.display = 'none';
	}
	if(document.getElementById('GM_thumb')){
		document.getElementById('GM_thumb').style.display = 'block';
	}
}

function GM_ShowThumbLink(){
	if(document.getElementById('gm_show_thumb')){
		document.getElementById('gm_show_thumb').style.display = 'block';
	}
}

function GM_ShowStreetviewLink(){
	if(document.getElementById('gm_show_streetview')){
		document.getElementById('gm_show_streetview').style.display = 'block';
	}
}

function GM_HideThumbLink(){
	if(document.getElementById('gm_show_thumb')){
		document.getElementById('gm_show_thumb').style.display = 'none';
	}
	if(document.getElementById('gm_sep')){
		document.getElementById('gm_sep').style.display = 'none';
	}
}

function GM_HideStreetviewLink(){
	if(document.getElementById('gm_show_streetview')){
		document.getElementById('gm_show_streetview').style.display = 'none';
	}
	if(document.getElementById('gm_sep')){
		document.getElementById('gm_sep').style.display = 'none';
	}
}

function GM_GenerateTriggerCallback(object, eventType){
	return function(){
		google.maps.event.trigger(object, eventType);
	};
}

function GM_ClickMarkerIndex(i){
	if(GM_MAP && GM_MARKERS[i]){
		google.maps.event.trigger(GM_MARKERS[i], 'click');
	}
}

// ####################################################################

function Search_QueryString(include_lat_lng){
	var qs = new Array();
	for(var index = 0; index < SEARCH_FIELDS.length; index++){
		if(document.getElementById(SEARCH_FIELDS[index])){
			var val = escape(jQuery('#' + SEARCH_FIELDS[index]).val());
			if(val){
				qs.push(SEARCH_FIELDS[index] + '=' + val);
			}
		}
	}
	if(include_lat_lng){
		qs.push('sw_lat=' + GM_BOUNDS.getSouthWest().lat());
		qs.push('sw_lng=' + GM_BOUNDS.getSouthWest().lng());
		qs.push('ne_lat=' + GM_BOUNDS.getNorthEast().lat());
		qs.push('ne_lng=' + GM_BOUNDS.getNorthEast().lng());
	}
	// load featured by default.
	if(document.getElementById('featured') && document.getElementById('featured').checked){
		qs.push('featured=1');
	//	qs.push('orderby=RAND()');
	}
	if(document.getElementById('open_house') && document.getElementById('open_house').checked){
		qs.push('open_house=1');
	}
	// if no result containers exist then just update session.
	if(! document.getElementById('gm_map') && ! document.getElementById('gm_results') && ! jQuery('.resultsCount').length){
		qs.push('update_only=1');
	}
	return qs.join('&');
}

function Search_ParseData(data){
	GM_InfoWindows_Delete();
	GM_Markers_Delete();
	GM_BOUNDS = new google.maps.LatLngBounds();
	data      = eval('(' + data + ')');
	if(data){
		if(data.listings && typeof data.listings[0] != 'undefined' && typeof data.listings[0].listing_id != 'undefined'){
			for(var i in data.listings){
				var marker = GM_ItemAdd(data.listings[i]);
				Search_AddResult(data.listings[i], marker);
			}
		}else{
			GM_Empty(true);
		}
		if(data.pager){
			Search_PagerUpdateDisplay(data.pager);
		}
	}
}

function Search_PagerUpdateDisplay(pager){
	if(jQuery('.resultsTools').length){
		var h = '<div class="resultsCount">Showing ' + pager.from + '-' + pager.to + ' of ' + pager.total + ' new homes</div>';
		if(pager.page_min != pager.page_max){
			h += '<div class="resultsPagination">';
			h += '<ul>';
			if(pager.page > 1){
				h += '<li><a href="javascript:;" onclick="Search_ShowPage(' + (pager.page-1) + ');" title="Previous">&lt;</a></li>';
			}
			if(pager.page > 3 && pager.page_max > 5){
				h += '<li>...</li>';
			}
			for(var i = pager.page_min; i <= pager.page_max; i++){
				if(i > pager.page - 3 && i < pager.page + 3){
					if(i == pager.page){
						h += '<li><a href="javascript:;" class="active" title="Page ' + i + '">' + i + '</a></li>';
					}else{
						h += '<li><a href="javascript:;" onclick="Search_ShowPage(' + i + ');" title="Page ' + i + '">' + i + '</a></li>';
					}
				}
			}
			if(pager.page < pager.page_max - 2 && pager.page_max > 5){
				h += '<li>...</li>';
			}
			if(pager.page < pager.page_max){
				h += '<li><a href="javascript:;" onclick="Search_ShowPage(' + (pager.page+1) + ');" title="Next">&gt;</a></li>';
			}
			h += '</ul>';
			h += '</div>';
			h += '<div class="clear"></div>';
		}
		jQuery('.resultsTools').html(h);
	}
}

function Search_ShowPage(p){
	jQuery.post('/templates/jrussell/remote/search.php?' + Search_QueryString(GM_ZOOMED) + '&page=' + p, function(data){
		Search_ParseData(data);
	});
}

function Search_AddMarkerLink(listing, marker){
	if(document.getElementById('gm_markers')){
		var ul         = document.getElementById('gm_markers');
		var li         = document.createElement('li');
		var aSel       = document.createElement('a');
		aSel.href      = 'javascript:void(0);';
		aSel.title     = (listing.listing_addr1 ? listing.listing_addr1 + ' ' : '') + (listing.listing_addr2 ? listing.listing_addr2 + ' ' : '') + (listing.listing_city ? listing.listing_city + ' ' : '') + (listing.listing_state ? listing.listing_state + ' ' : '') + (listing.listing_zip ? listing.listing_zip : '');
		aSel.innerHTML = listing.listing_title;
		aSel.onclick   = GM_GenerateTriggerCallback(marker, 'click');
		li.appendChild(aSel);
		ul.appendChild(li);
	}
}

function Search_AddResult(listing, marker){
	if(document.getElementById('gm_results')){
		var h = '<div class="homeListing">';
		if(listing.listing_image){
			h += '<div class="homeListing-image"><a href="' + Search_GetListingLink(listing) + '" title="' + listing.listing_title + (listing.listing_city || listing.listing_state ? ' - ' : '') + listing.listing_city + (listing.listing_city && listing.listing_state ? ', ' : '') + listing.listing_state + '"><img src="/image2.php?type=listing&id=' + listing.listing_id + '&file=' + listing.listing_image + '&size=mid&banner=1" alt="' + listing.listing_title + (listing.listing_city || listing.listing_state ? ' - ' : '') + listing.listing_city + (listing.listing_city && listing.listing_state ? ', ' : '') + listing.listing_state + '"/></a>';
		}else{
			h += '<div class="homeListing-image"><a href="' + Search_GetListingLink(listing) + '" title="' + listing.listing_title + (listing.listing_city || listing.listing_state ? ' - ' : '') + listing.listing_city + (listing.listing_city && listing.listing_state ? ', ' : '') + listing.listing_state + '"><img src="/templates/jrussell/images/imagenotavailable_md.jpg" alt="' + listing.listing_title + (listing.listing_city || listing.listing_state ? ' - ' : '') + listing.listing_city + (listing.listing_city && listing.listing_state ? ', ' : '') + listing.listing_state + '"/></a>';
		}
		h += '</div>';
		h += '<div class="homeListing-details">';

		h += (listing.listing_title ? '<span class="span_listing_title"><a href="' + Search_GetListingLink(listing) + '" title="' + listing.listing_title + (listing.listing_city || listing.listing_state ? ' - ' : '') + listing.listing_city + (listing.listing_city && listing.listing_state ? ', ' : '') + listing.listing_state + '" class="homeListing-name">' + (listing.listing_title.length > 35 ? '<span title="' + listing.listing_title + '">' + listing.listing_title.substring(0, 32) + '...</span>' : listing.listing_title) + '</a></span><br />' : '');
		h += (listing.listing_price != 0 ? '<span class="span_listing_price"><b>Price:</b> <span class="price">$' + listing.listing_price + '</span></span><br />' : '');
		h += (listing.category_name ? '<span class="span_listing_community"><b>Community:</b> ' + (listing.category_name.length > 25 ? listing.category_name.substring(0, 22) + '...' : listing.category_name) + '</span><br />' : '');

		h += (listing.fields__bed ? '<span class="span_listing_bed"><b>Bedrooms:</b> ' + listing.fields__bed + '</span>' : '');
        h += (listing.fields__garage ? '<span class="span_listing_garage"><b>Garage:</b> ' + listing.fields__garage + '</span>' : '');
        h += '<div class="clear"></div>';
		h += (listing.fields__bath ? '<span class="span_listing_bath"><b>Bathrooms:</b> ' + listing.fields__bath + '</span>' : '');
		h += (listing.fields__sqft ? '<span class="span_listing_sqft"><b>Sq. Ft.:</b> ' + listing.fields__sqft + '</span>' : '');
		h += '<div class="clear"></div>';
		h += '<a href="' + Search_GetListingLink(listing) + '" title="' + listing.listing_title + (listing.listing_city || listing.listing_state ? ' - ' : '') + listing.listing_city + (listing.listing_city && listing.listing_state ? ', ' : '') + listing.listing_state + '" class="homeListing-more">Home details &raquo;</a>';
		h += '</div><!-- homeListing-details -->';
		h += '<div class="clear"></div>';
		h += '</div><!-- homeListing -->';
		document.getElementById('gm_results').innerHTML += h;
	}
}

function Search_GetListingLink(listing){
	var a = new Array();
	if(listing.listing_addr1){
		a[a.length] = listing.listing_addr1;
	}
	if(listing.listing_addr2){
		a[a.length] = listing.listing_addr2;
	}
	if(listing.listing_city){
		a[a.length] = listing.listing_city;
	}
	if(listing.listing_state){
		a[a.length] = listing.listing_state;
	}
	if(listing.listing_zip){
		a[a.length] = listing.listing_zip;
	}
	return '/Property/' + ((listing.category_name ? listing.category_name + '/' : '') + (listing.listing_title && listing.listing_title != listing.listing_addr1 ? listing.listing_title + '/' : '') + (a.length ? a.join(' ').replace(/\//g, '') : 'unknown') + '/' + listing.listing_id).replace(/ /g, '_');
}

function Search_LatLng_Change(){
	GM_Wait(true);
	Search_FlashFeatured();
	Search_FlashOpenHouse();
	jQuery.post('/templates/jrussell/remote/search.php?' + Search_QueryString(true), function(data){
		GM_ZOOMED = true;
		Search_ParseData(data);
		GM_Wait(false);
	});
}

function Search_Feature_Change(){
	GM_Wait(true);
	Search_FlashOpenHouse();
	jQuery.post('/templates/jrussell/remote/search.php?' + Search_QueryString(), function(data){
		GM_ZOOMED = false;
		Search_ParseData(data);
		GM_Wait(false);
	});
}

function Search_OpenHouse_Change(){
	GM_Wait(true);
	Search_FlashFeatured();
	jQuery.post('/templates/jrussell/remote/search.php?' + Search_QueryString(), function(data){
		GM_ZOOMED = false;
		Search_ParseData(data);
		GM_Wait(false);
	});
}

function Search_Category_Change(){
	GM_Wait(true);
	Search_FlashFeatured();
	Search_FlashOpenHouse();
	jQuery.post('/templates/jrussell/remote/search.php?' + Search_QueryString(), function(data){
		GM_ZOOMED = false;
		Search_ParseData(data);
		GM_Wait(false);
	});
}

function Search_Builder_Change(){
	GM_Wait(true);
	Search_FlashFeatured();
	Search_FlashOpenHouse();
	jQuery.post('/templates/jrussell/remote/search.php?' + Search_QueryString(), function(data){
		GM_ZOOMED = false;
		Search_ParseData(data);
		GM_Wait(false);
	});
}

function Search_Price_Change(){
	GM_Wait(true);
	Search_FlashFeatured();
	Search_FlashOpenHouse();
	jQuery.post('/templates/jrussell/remote/search.php?' + Search_QueryString(), function(data){
		GM_ZOOMED = false;
		Search_ParseData(data);
		GM_Wait(false);
	});
}

function Search_Bed_Change(){
	GM_Wait(true);
	Search_FlashFeatured();
	Search_FlashOpenHouse();
	jQuery.post('/templates/jrussell/remote/search.php?' + Search_QueryString(), function(data){
		GM_ZOOMED = false;
		Search_ParseData(data);
		GM_Wait(false);
	});
}

function Search_Bath_Change(){
	GM_Wait(true);
	Search_FlashFeatured();
	Search_FlashOpenHouse();
	jQuery.post('/templates/jrussell/remote/search.php?' + Search_QueryString(), function(data){
		GM_ZOOMED = false;
		Search_ParseData(data);
		GM_Wait(false);
	});
}

function Search_Sqft_Change(){
	GM_Wait(true);
	Search_FlashFeatured();
	Search_FlashOpenHouse();
	jQuery.post('/templates/jrussell/remote/search.php?' + Search_QueryString(), function(data){
		GM_ZOOMED = false;
		Search_ParseData(data);
		GM_Wait(false);
	});
}

function Search_Area_Change(){
	GM_Wait(true);
	Search_FlashFeatured();
	Search_FlashOpenHouse();
	jQuery.post('/templates/jrussell/remote/search.php?' + Search_QueryString(), function(data){
		GM_ZOOMED = false;
		Search_ParseData(data);
		GM_Wait(false);
	});
}

function Search_SchoolDistrict_Change(){
	GM_Wait(true);
	Search_FlashFeatured();
	Search_FlashOpenHouse();
	jQuery.post('/templates/jrussell/remote/search.php?' + Search_QueryString(), function(data){
		GM_ZOOMED = false;
		Search_ParseData(data);
		GM_Wait(false);
	});
}

function Search_Reset(){
	for(var index = 0; index < SEARCH_FIELDS.length; index++){
		var val = escape(jQuery('#' + SEARCH_FIELDS[index]).val());
		if(document.getElementById(SEARCH_FIELDS[index])){
			document.getElementById(SEARCH_FIELDS[index]).options.selectedIndex = 0;
		}
	}
	document.getElementById('featured').checked = false;
	document.getElementById('open_house').checked = false;
	Search_Category_Change();
}

// flash featured checkbox and label if checkbox is checked.
function Search_FlashFeatured(){
	var $e = jQuery("#featuredCheckbox");
	var $c = jQuery("#featured");
	if($e.length && $c.length && $c.attr('checked')){
		Search_FlashElement($e);
	}
}

// flash open house checkbox and label if checkbox is checked.
function Search_FlashOpenHouse(){
	var $e = jQuery("#openhouseCheckbox");
	var $c = jQuery("#open_house");
	if($e.length && $c.length && $c.attr('checked')){
		Search_FlashElement($e);
	}
}

function Search_FlashElement($e){
	if($e){
		$e.fadeOut('fast', function(){
			$e.fadeIn('fast', function(){
				$e.fadeOut('fast', function(){
					$e.fadeIn('fast', function(){
						$e.fadeOut('fast', function(){
							$e.fadeIn('fast', function(){
								// nothing to do here.
							});
						});
					});
				});
			});
		});
	}
}

// ####################################################################
