//window.loadFirebugConsole(); 
//	var $ = jQuery.noConflict();

    var map;
    var initialZoom = 15;
    var initialFit = true;
    
// Marker icons in various colors
	var colors = new Array('red','green','silver','yellow','orange','gold','blue');
	
	var bounds;
	var icons=[];
	var gmarkers=[];
	var defMarker;
	var lat = 39.797063;	// 6104 E 21st St
	var lon = -86.060865;
	var address = '';
	var tooltip = address;
	var summary = '';
	var title = '';
	var pic = '';
	var request = '';
	var markerMgr;
	var gridimgpath = '/js/jqGrid/themes/black/images';
	var gridrows = 0;
	var initializing = true;
	var mouseX;
	var mouseY;
	var id='';
	var idlist='';  // An array extracted from jGrid representing all checkmarked rows
	var t_no='';
	var item_n = 0;
	var item_total = 1;
	var timer;
	var last_request = '';
	var grid;
	var viewall=0;
	var draggableMarkers = false;
	var x0=.0009;
	var y0=.0009;
	var trimedge = '&y='+y0+'&x='+x0; 
	var cancel = false;
	var cookieFavorites = 'rrg_favorites';
	var favorites = '';
	var find_exact=false;
	var globalParams = new Array();
	
	centerpoint = document.location.toString().split('?')[1];
	if (centerpoint) {
		centerpoint = centerpoint.split("&");
		var i, param;
		for (i=0;i<centerpoint.length;i++) {
			param = centerpoint[i].split('=');
			if (param[0] == 'lat') 	lat		= parseFloat(param[1]);
			if (param[0] == 'lon') 	lon		= parseFloat(param[1]);
			if (param[0] == 'id')  {id = param[1];  if (id != 'myfavs') {id = parseInt(id);}}
			if (param[0] == 't_no')	t_no	= param[1];
			if (param[0] == 't_nolist')	t_no= param[1];  // Alias for t_nos
			if (t_no.split(',').length > 1) find_exact = true;  // Gave a list of t_no's, so do exactly that and nothing else
			if (param[0] == 'all')	viewall	= param[1];
			if (param[0] == 'idlist') {
										find_exact = true;
										idlist	= param[1]; 						// Enable us to 'map checked items' from some other page
										idlist	= idlist.split(',');  				// URL parameter, parsed into an array as if it was produced by jGrid
										id		= idlist[0].toString();				// Pick off the first item for use as the 'center' of the map
									  }
		}
	}

$(function() {
// Collect input parameters we need to pass to other pages
	var top; var bottom; var title; var refer; var key;
		if (top = getParam('top')) 			 globalParams.push('top='+top);
		if (bottom = getParam('bottom')) 	 globalParams.push('bottom='+bottom);
		if (title = getParam('title')) 	 	 globalParams.push('title='+title);
		if (referral = getParam('referral')) globalParams.push('referral='+referral);
		if (key   = getParam('key'))   	 	 globalParams.push('key='+key);
		globalParams = globalParams.join('&');
		if (find_exact) {
			$("input#freeze").attr('checked',false);
		}
	grid = $("table#listing");
// Monitor the window resize event and let the map know when it occurs
		$(window).resize( 
			function(e)  {
					map.checkResize();
					if ($("input#freeze").attr('checked'))
						refreshMarkers();
			} 
			); 
		$(window).unload( 
			function(e)  {
					GUnload();  // Avoid memory leak in google map
			} 
			); 

		$("a.detail").click(
			function() {
				var idarray;
				if (idarray = $("#listing").getGridParam('selarrrow')) {
					var params='';
					var i;
					for (i = 0; i < idarray.length; i++)
						window.open('/detail.php?id='+idarray[i],'/detail'+idarray[i]);
					return false;
				}
			}
			);
		$("a.photolist").click( // Display photo list page for selected items
			function() {
				var list;
				if (list = $("#listing").getGridParam('selarrrow').join(',')) {
					var params='';
					if (params = window.location.toString().split('?')[1])
						if (params = removeParam(params,'idlist')) params = "&" + params;
							this.href = this.href.split('?')[0] + '?idlist=' + list + params;
				}
				else {
					addMapAlert("Please select at least<br>one item first.", 1000);
					return false;
				}
			}
			);
		$("a.flyer").click( // Display photo list page for selected items
			function() {
				var list = $("#listing").getGridParam('selarrrow');
				if (!list)
					 list = $("#listing").getDataIDs();
				if (list) {
					var image_idx = list.length-1; // 3 listings = bottom2, 4 listings = bottom3
					if (image_idx > 3) image_idx = 3;
					var $ovr;
					if ($ovr = $("input[name='bottom_ovr']").val()) {
						image_idx = $ovr;
					}
					list = list.join(',');
					var params='';
						params = window.location.toString().split('?')[1];
						params = removeParam(params,'idlist');
							if (params=='') params += '?'; else params +='&';
							params += "bottom="+image_idx;
							this.href = this.href.split('?')[0] + '?idlist=' + list + '&' + params;
				}
				else {
					addMapAlert("At leastone item must be<br>in the list to create the flyer.", 1000);
					return false;
				}
			}
			);
		$("a.mapchecked").click( // Remove markers that are not checked (reload map with idlist)
			function() {
				var list;
				if (list = $("#listing").getGridParam('selarrrow').join(',')) {
					var params='';
					if (params = window.location.toString().split('?')[1])
						if (params = removeParam(params,'idlist')) params = "&" + params;
					this.href = this.href + '?idlist=' + list + params;
					clearMarkers();
					$("input#freeze").attr('checked',false);
					refreshMarkers();
				}
				else {
					addMapAlert("Please select at least<br>one item first.", 1000);
					return false;
				}
			}
			);
		$("a.checked").click(
			function() {
			}
		);
		$("a.print").click(
			function() {
				window.print();
				return false;
			}
			);
			
    if (GBrowserIsCompatible()) {
	    $("#map").height($(window).height()*.6); // Assign the portion of screen height for map area
	    initMap("map", lat, lon);
	    

    }
// Track mouse movement for popup placement
    $().mousemove(function(e){
      mouseX = e.pageX;
      mouseY = e.pageY;
    });
    
	initGrid(grid);
	
});
function removeParam(list, val) {
// Strip a parameter out of the parameter list
	var items = list.split('&');
	var i;
	var params = new Array();
	for (i=0;i<items.length;i++) {
		if (items[i].split('=')[0] != val)
			params.push(items[i]);
	}
	return params.join('&');
}
function clearMarkers() {
	var i;
	for (i=0;i<gmarkers.length;i++)
		markerMgr.removeMarker(gmarkers[i]);
	gmarkers = [];
	$("#listing").clearGridData();
	gridrows = 0;
	item_n = 1;
	viewall=0;
}
function initGrid(thisGrid) {	
// The grid list of properties
	var gridtitle = $("title").html().split(',');
	gridtitle = gridtitle[0];

thisGrid.jqGrid(
		{ 
		url:'',
		datatype: "json", 
		colNames:['#',translations.location,translations.grade,'',translations.br, translations.ba, translations.gar,translations.down,translations.monthly,translations.price], 
		colModel:[ {name:'nbr', index:'nbr', align:"center", width:20},
				   {name:'location',index:'location', width:150}, 
				   {name:'grade',index:'grade',width:38, align:"center"},
				   {name:'status', index:'status', width:35, align:"center"},
				   {name:'br',index:'br', width:38, align:"center"}, 
				   {name:'ba',index:'ba', width:38, align:"center"}, 
				   {name:'gar',index:'gar', width:48, align:"center"}, 
				   {name:'down',index:'down', width:60, align:"center"}, 
				   {name:'monthly',index:'monthly', width:43,align:"center"}, 
				   {name:'price',index:'price', width:73,align:"center"}
				 ], 
				 rowNum:25, 
				 imgpath: gridimgpath, 
				 sortname: 'id', 
				 viewrecords: true, 
				 sortorder: "desc", 
				 multiselect: true, 
				 loadonce: true,
				 forceFit: true,
				 expandColumn: 'price',
				 width: 616,
				 hidegrid: false,
				 recordtext: 'Properties',
				 caption: $("title").attr('id') + gridtitle,
				 onSelectRow:
	function(id, stat) {
		setCheckbox('input#pop_'+id, stat);
	},
				 afterInsertRow: 
    function (id, rowdata) {
	    
            var distance = 10;
            var time = 250;
            var hideDelay = 500;

            var hideDelayTimer = null;

            var beingShown = false;
            var shown = false;
            var trigger = $('.location', this);
            var info = $('.picpop').css('opacity', 0);
            restoreCheckmark(id);
            // Event for the display/hide of the house thumbnail
			$("img#poppic_"+id).click(
				function() {
				if (hideDelayTimer) clearTimeout(hideDelayTimer);
				if (!shown) {
            	    if (beingShown || shown) {
            	        // don't trigger the animation again
            	        return;
            	    } else {
            	        // reset position of info box
            	        beingShown = true;
						$('.picpop img').attr('src', $(this).attr('ref'));
            	        info.css({
            	            top: $(this).offset().top-42,
            	            left: $(this).offset().left+150,
            	            display: 'block'
            	        }).animate({
            	            left: '-=' + distance + 'px',
            	            opacity: 1
            	        }, time, 'swing', function() {
            	            beingShown = false;
            	            shown = true;
            	        });
            	    }
            	    return false;
        	    }
				}).mouseout(
				function() {
            	    hideDelayTimer = setTimeout(function () {
            	        hideDelayTimer = null;
            	        info.animate({
            	            left: '-=' + distance + 'px',
            	            opacity: 0
            	        }, time, 'swing', function () {
            	            shown = false;
            	            info.css('display', 'none');
            	        });

            	    }, hideDelay);
            	    
            	return false;

			});
		}
		}
	).navGrid('#pager', {add:false,del:false,edit:false,position:"right"}); 
}	

// Supporting functions for map
function loadList() {
// Load properties in the list of id's, e.g. "1,2,3,..."

	$("input#freeze").attr('checked',(idlist ? false : true));  // Don't expand search if a specific list was requested
	refreshMarkers();

}
function refreshMarkers() {
	
	map.checkResize();
//	if ($("input#freeze").attr('checked')) idlist = '';  // Then go for all markers again
	
var bounds = map.getBounds();
	request =	'http://' + location.host + '/shared_content/map_nearby_properties2.php'+
				'?&id='+id+'&t_no='+t_no+'&idlist='+idlist+'&all='+viewall;
//	if (!initializing) {
	var near = find_exact ? 0 : 1;  //  Don't look for other properties if an idlist was requested
		request +=  '&near='+near+
					'&y1='+bounds.getSouthWest().lat()+'&x1='+bounds.getSouthWest().lng()+
					'&y2='+bounds.getNorthEast().lat()+'&x2='+bounds.getNorthEast().lng()+ trimedge;
//	}
    if (viewall || (last_request != request)) {
	    last_request = request;
		$.getJSON(request,
		    function(data, status){
			    function doAdd(items) {
		    		addProperty(items[item_n]);  // To map
				    item_n++;
    				progress(item_n,item_total);
    				if (item_n < item_total)
    					if (!cancel) 
    						setTimeout(callDoAdd(items),5);
    					else {
    						$("div#progress").remove(); addMapAlert("Cancelled",1000);fitMapToMarkers();
		    				initializing = false; // Turn off after initial set of markers is loaded
						}
    				else {
//						if (!initializing) makeFit();
	    				if (idlist || find_exact) fitMapToMarkers();
    					$("div#progress").remove();
	    				initializing = false; // Turn off after initial set of markers is loaded
					}
			    }
			    function callDoAdd(items) {
				    return function() {
										doAdd(items);
									  }
			    }
			    item_total = data.markers.length;
			    item_n = 0;
			    if (item_total > 1) {
					$("div#map:not(:has('div#progress'))").append("<div class='noprint' id='progress'>Loading...&nbsp;<a title='Click to abort' id='cancel' href='#'><img src='/css/intl-no.gif'/></a></div>");
					$("a#cancel").click(
									function() {
											cancel = 1;
									}
					);
					$("div#progress").progressBar({
	       										boxImage: '/images/progressbar.gif', 
       											barImage: '/images/progressbg_green.gif'
       										  });
				}

		   		setTimeout(callDoAdd(data.markers),100);

	  		}
	  	);
	}
}
function makeFit() {
	
// Ensure all the initially-shown markers fit within the window
//	addMapAlert('<b>Scaling map to fit...</b>',2000);
	if (initialFit) {initialFit = false; map.setZoom(15);};  // else fitMapToMarkers();
	trimedge='';
}
function progress(cur,total) {
   	$("div#progress").progressBar(Math.floor(100 * (cur/total)));
}
function defaultMarker() {
		defMarker = new GIcon();
		defMarker.image = coloredIcon('silver');		
		defMarker.iconSize = new GSize(21, 31);
		defMarker.iconAnchor = new GPoint(7, 30);
		defMarker.infoWindowAnchor = new GPoint(20,30);
}
function initMap(container, lat, lng) {
      	map = new GMap2(document.getElementById(container));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());

		initCenter();	// Center map on selected property
//  The map seems to go into 'drag' mode in Firefox, even without holding the mouse down
	jQuery.each(jQuery.browser, function(i) {
		if(!$.browser.msie){
			map.disableDragging();		// Turn it off (turn it back on when done adding markers)
		}
	});
		GEvent.addListener(map,'moveend',
			function() {
				if ($("input#freeze").attr('checked'))
					refreshMarkers();
			}
		);
		GEvent.addListener(map,'zoomend',
			function() {
				if ($("input#freeze").attr('checked'))
					refreshMarkers();
			}
		);

		GEvent.addListener(map, "mouseover", function(){
			map.showControls();
		});
		GEvent.addListener(map, "mouseout", function(){
			map.hideControls(); 
		});
/* Disable resizer bar 2008-11-26
		$("#map").resizable({
							handles: "s",
							stop: function(e,ui) {
													if ($("input#freeze").attr('checked'))
														refreshMarkers();
												 }
							});
*/
}
function initCenter() {
	request =	'http://' + location.host + '/shared_content/map_nearby_properties.php'+
				'?&id='+id+'&t_no='+t_no+'&idlist='+idlist+'&near=0';
		$.getJSON(request,
			function(data, status) {
				var lat_c = data.lat;
				var lon_c = data.lon;
				map.setCenter(new GLatLng(lat_c,lon_c), initialZoom, G_NORMAL_MAP);
				markerMgr = new MarkerManager(map);
				defaultMarker();
		
				// Now load the initial set of markers 
					if (idlist || viewall)
						loadList();			// When a comma-separated list of properties is provide, start out by loading them
					else
					if (id || t_no)
						refreshMarkers();
			}
		);
}
function coloredIcon(iconColor) {
   var color;
   if ((typeof(iconColor)==undefined) || (iconColor==null)) { 
      color = "red" 
   } else { 
      color = iconColor; 
   }
   if (!icons[iconColor]) {
      var icon = new GIcon(defMarker);
      icon.image = "markers/color/"+ color +".png";
      icons[iconColor]=icon;

   } 
   return icons[iconColor];
}
function toggleCheckbox(cb) {
	var stat = $(cb).attr('checked') ? $(cb).attr('checked', false) : $(cb).attr('checked', true);
}
function setCheckbox(cb, stat) {
	$(cb).attr('checked', stat);
}
function copyCheckbox(cb1,cb2) {
	$(cb1).attr('checked',$(cb2).attr('checked'));
}
function addProperty(item){
	if (item == undefined) return;
   var point = new GLatLng(item.lat, item.lon);
   var i;
  
   if (bounds) bounds.extend(point);
 	if (gmarkers)
	for (i=0;i< gmarkers.length;i++)
		if ((gmarkers[i].uid == item.id)) return;  // No need to re-add it

   	if (parseInt(item.selected)==1) {
	   		map.setCenter(point);
   	}

// Create numbered markers (number corresponds to the line number in the grid list

var L = gmarkers.length+1;
var P = (item.code =="A") ? (item.selected=='1' ? '#00ff00' : '#ff0000') : "#999999";  // Gray-out inactive properties
	if (item.code=='P' || item.code=='S') P = "#999999";
var C = item.selected=='1' ? '#000000' : '#ffffff';

var ico = MapIconMaker.createFlatIcon({width: 24, height: 24, primaryColor: P, label: L.toString(), labelColor: C, labelSize:11});
	ico.iconSize = new GSize(24, 24);
	ico.iconAnchor = new GPoint(24,0);
	ico.infoWindowAnchor = new GPoint(24,0);
var marker = new GMarker(point, {icon: ico, draggable: draggableMarkers, title: item.street, zIndexProcess:importanceOrder});
	marker.importance = item.selected=='1' ? 2 : 1;
	marker.uid	= item.id;

   marker.index = gmarkers.length;

   gmarkers.push(marker); 
// HTML for the popup
var cb1 = 'pop_' + item.id;
var cb2 = 'input#jqg_' + item.id;
var checked = rowIsChecked(item.id) ? 'checked' : '';

var chk = '"input#' + cb1 + '"';
var onclick = "onclick='toggleCheckbox(" + '"' + cb2 + '"' + ");'";
var onload  = "onload='alert(item.id)'";
var title = translations.viewpopup + ' ' + translations.detail;
var bubble = " \
		<div class='bubble'> \
		<input type='checkbox' value='"+item.id+"' name='selection' class='selection' id=" + cb1 + " " + onclick + " " + checked + "/> \
		<img class='closer' src='/images/close.gif' /> \
		<blockquote> \
		<a href='/detail.php?id=" +item.id+ "' target='_blank'><img title='" +title+ "' class='house' src='" + item.pic + "' /></a> \
		<div> \
			<h1>" + item.street + "</h1> \
			<h2>" + item.citystate + "</h2> \
			<table class='detail'> \
			<tr> \
			<th>" + translations.monthly + ":</th><td>" + item.monthly + "</td><th>" + translations.down + ":</th><td>" + item.down + "</td> \
			</tr> \
			<tr> \
			<th>"+ translations.br +":</th><td>" + item.br + "</td><th>"+ translations.ba + ":</th><td>" + item.ba + "</td> \
			</tr> \
			</table> \
		</div> \
		<b class='marker'>"+translations.markernum+"&nbsp;<img src='" + ico.image + "'/></b> \
		</blockquote> \
		</div>";
	marker.bubble = bubble;

   GEvent.addListener(marker, "click", function () {
	   if ($("div.bubble").length)
	   	$("div.bubble").remove();
		$("body").append(this.bubble);
		var w = $("div.bubble").width(); w = 266;
		var h = $("div.bubble").height();h = $("div.bubble").height();
		var x = (mouseX+w > $(window).width()) ? mouseX-w-30 : mouseX+30;
		var y = (mouseY+h > $(window).height()) ? mouseY-h-30 : mouseY;
		if (x < 0) x = 10;
		if (y < 0) y = 10;
		$("div.bubble").css('top',y+'px').css('left',x+'px').css('position','absolute');
		$("div.bubble input").attr('checked',rowIsChecked($("div.bubble input").val()));
	    $("img.closer").click(
	    	function() {
		    	$(this).parent().remove();
	    	}
	    );
    
    	$.preload("div.bubble img.house", {placeholder:'../images/NOphoto.jpg',notFound:'../images/NOphoto.jpg'});
	}); // end addListener
		GEvent.addListener(marker, "dragend", function() {
			addMapAlert('Marker moved to:<br> ('+ marker.getLatLng().lat() + ', ' + 	marker.getLatLng().lng()	 + ')',2500);
		});
 
	markerMgr.addMarker(marker,5);
	
/*
	var url = '/shared_content/get_property_single.php?q=2&nd='+new Date().getTime()+'&id='+item.id;
	// Get data for the grid/list section
   	$.getJSON(url,
					function(row) {
						addRow(row);
		   			  }
		   		);
*/
 		addRow(item.gridrow)
}
function addRow(row) {
	row.rowdata['nbr'] = ++gridrows;
	$("#listing").addRowData(row.id,row.rowdata);
	}
function addMapAlert(msg, interval) {
	$("div#map").append("<div id='scaling' class='noprint'>"+msg+"</div>");
	setTimeout("$('div#scaling').remove()",interval);
}
function fitMapToMarkers() {
	if (gmarkers.length > 1) {
		var markersBounds=new GLatLngBounds(), i;
		for(i=gmarkers.length-1; i>=0; i--){
			markersBounds.extend(gmarkers[i].getLatLng());
		}
		var fitMapToMarkersZoom = map.getBoundsZoomLevel(markersBounds);
		map.setCenter(markersBounds.getCenter(), fitMapToMarkersZoom);
	}
	else
		if (gmarkers.length == 1)
			map.setCenter(gmarkers[0]);  // Just center it, don't change the zoom level
};
function importanceOrder (marker,b) {
	return GOverlay.getZIndex(marker.getPoint().lat()) + marker.importance*1000000;
}

function SetCookie(cookieName,cookieValue,nDays) {
	var today = new Date();
	var expire = new Date();
	if (nDays==null || nDays==0 || nDays===undefined) nDays=1;
	expire.setTime(today.getTime() + 3600000*24*nDays);
	document.cookie = cookieName+"="+escape(cookieValue)
	             + ";expires="+expire.toGMTString();
}

function GetCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}
	function restoreCheckmark(id) {
	// Restore any prior checkbox selection after the row has been loaded
			if (rowIsChecked(id)) grid.setSelection(id);
	}
	function rowIsChecked(id) {
		var favorites;
		var cookie = GetCookie(cookieFavorites);
		if (cookie===null || cookie == '') {
			favorites = new Array(); 
		}
		else {
			favorites = cookie.split(',');
		}
		var i;
		
		for (i=1;i<=favorites.length;i++) {
			if (id == favorites[i-1]) return true;
		}
	return false;
}
function getParam(p) {
	var params = location.search.split('&');
	var i;
	var item;
	for (i=0; i<params.length;i++) {
		item = params[i].split('=');
		if (item[0] == p) {
			return item[1];
		}
	}
	return '';
}