/**
* Copyright (c) 2006 Mashup Technologies LLC. All Rights Reserved.
* http://www.mapbuilder.biz
*
* This code (including but not limited to the actual source code, documentation and database schemes) 
* is not freeware and is intended for the use of the original license purchaser according to the license agreement.
* The code all or in part may not be sold, redistributed, or included as part of another application.
* 
* THIS SOFTWARE PRODUCT IS PROVIDED "AS IS" AND LICENSOR MAKE NO WARRANTY AS TO ITS USE, PERFORMANCE, 
* OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ 

// Reverted to Sep 12 version b/c detail area stopped working KJ 10/5

var App = {
	Version: '2.0.1',
	cma: false, // does this run in CMA app
	debug: false,
	LogReader: null, 
	LogWriter: null,

	DataFeed: null,
	PropertyFeed: null,
	gMap: null, 
	gIcons: [], 
	gmarkers: [],
	activeMarker: null,
	activeMarkerID: null, 
	isValue: false,
	
	//Tooltip functionality
	flipMarkers: true,
	tooltip: null,
	tooltipTable: null,


	// Sidebar
	sideBarHtml: "",
	// Background color of an active row
	sideBarRowActive: "#EFD2A4",
	sideBarRowOver: "#E4E2D4",
	scrollSidebar: false,

	Table: null,
	Rows: new Array(),
	
	//data object
	jsonData: null,
	imgURL: "http://photos.flexmls.com/sbr/",
	

	// KJ added
	neighborhood: "Mesa",
	currentSearchType: null,

	setNeighborhood: function(N) {
	    if (N) {
		this.neighborhood = N;
	    }
	},


	load: function() {
		if((typeof Prototype=='undefined') || 
		parseFloat(Prototype.Version.split(".")[0] + "." +
					Prototype.Version.split(".")[1]) < 1.4)
		throw("MapObject requires the Prototype JavaScript framework >= 1.4.0");

		// Instantiate a logreader and a logwriter, also init map if possible
		Event.observe(window, 'load', this.init.bind(this)); 
	},

	init: function() {
		if (this.debug)
		{
			this.LogReader= new YAHOO.widget.LogReader(null, {right:"10px"});
			this.LogWriter = new YAHOO.widget.LogWriter("App Log Writer");
			this.LogWriter.log("Init  Started", "info");
		}
			
		if (GBrowserIsCompatible()) {

			//First of all, add event to free resources on window unload
			Event.observe(window, 'unload', GUnload); 
			
			//Create SideBar table
			this.Table = document.createElement("table");
			this.Table.className="General";
			this.Table.cellPadding="0";
			this.Table.cellSpacing="0";
			this.TBody = document.createElement('tbody');
			this.Table.appendChild(this.TBody);

			//Build icons
			this.loadData();

			// Register sidebar events
			//this.sideBarHtml += '<a href="javascript:myclick(' + id + ')" onmouseover="mymouseover('+id+')" onmouseout="mymouseout('+id+')">' + name + '</a><br>';
			var sideBar = document.getElementById("sideBar");
			Event.observe(sideBar, 'click', this.sideBarOnClick.bind(this)); 
			Event.observe(sideBar, 'mouseover', this.sideBarOnMouseOver.bind(this)); 
			Event.observe(sideBar, 'mouseout', this.sideBarOnMouseOut.bind(this)); 

		}
		else {
			alert("Sorry, the Google Maps API is not compatible with this browser");
		}
	},

	loadData: function()
	{
	    // We are using JSON instead of XML
		// Read the data from example.xml
		/* AJAX XML CAll
		/*
		var request = GXmlHttp.create();
		request.open("GET", "../data/example_xml.php", true);

		request.onreadystatechange = function() {

			
			if (request.readyState == 4) {
				var oTimer = new Util.Timer();
				var xmlDoc = request.responseXML;
				// obtain the array of markers and loop through it
				var markers = xmlDoc.documentElement.getElementsByTagName("marker");
          
				for (var i = 0; i < markers.length; i++) {
					// obtain the attribues of each marker
					var lat = parseFloat(markers[i].getAttribute("lat"));
					var lng = parseFloat(markers[i].getAttribute("lng"));
					var point = new GLatLng(lat,lng);
					var html = markers[i].getAttribute("html");
					var label = markers[i].getAttribute("label");
					// create the marker
					var marker = createMarker(point,label,html);

				}
				// put the assembled sideBarHtml contents into the sideBar div
				document.getElementById("sideBar").innerHTML = this.sideBarHtml;

			    if (this.debug) this.LogWriter.log(oTimer.Tick(1, "Loding finished: "), "time");
			}


		}
		request.send(null);
		*/

		// ****************************************************************
		// Fetch the JSON data file 
        if (this.debug) this.LogWriter.log("Going to download data ...");
		//GDownloadUrl("../data/example2.json", processData);
		//DEV GDownloadUrl("../data/homeexploring_opt1.js", this.processData.bind(this));

		//GDownloadUrl("service/FeedJSON_gz.php", this.processData.bind(this));
        
		GDownloadUrl(this.DataFeed, this.processData.bind(this));		

		// ****************************************************************
	},

	// ****************************************************************
	// Define the function thats going to process the JSON file
	processData: function(doc) {
        if (this.debug) this.LogWriter.log("Data received...");
		var oTimer = new Util.Timer();
		
		// UI Processing
	  	document.getElementById('LoadingImage').style.display = "none";
	  	document.getElementById('map').style.display = "block";
		// EOF UI Processing

		// load map 
		this.loadMap();

		// Parse the JSON document
		if(doc == null || doc == '') {
			this.loadData();
		}else{
			
		this.jsonData = eval('(' + doc + ')');
		
        	
		var lat = null;
		var lng = null;
		var point = null;

		// Set page header
		//document.getElementById("MapTitle").innerHTML = this.jsonData.map.title;
		//document.getElementById("MapDescription").innerHTML = this.jsonData.map.info.note;

		// Set map center and zoom
		//this.gMap.addControl(new GLargeMapControl());
		this.gMap.addControl(new GSmallMapControl());
		this.gMap.addControl(new GMapTypeControl());
		this.gMap.setCenter(new GLatLng(parseFloat(this.jsonData.map.lat), parseFloat(this.jsonData.map.lng)), parseFloat(this.jsonData.map.zoom));

		// set up marker mouseover tooltip div
		this.tooltip = document.createElement("div");
		this.tooltip.setAttribute('class', 'tooltip');

		this.gMap.getPane(G_MAP_FLOAT_PANE).appendChild(this.tooltip);
		this.tooltip.style.visibility="hidden";

		// *************** Build icons ***************
		this.buildIcons();
		
		// *************** Search & Build markers ***************
		this.doSearch();

		if (this.debug)
		{
			this.LogWriter.log("No of Markers downloaded: " + this.jsonData.map.markers.length, "info");
            this.LogWriter.log(oTimer.Tick(1, "Data processing finished in "), "time");
		}

	 // Loop through first 10 properties to find the first one with an image
   // and default to that property - the markers aren't in integer order
		if(App.jsonData.map.markers != null){
		for (i = 0; i < 10; i++) {
			if(App.jsonData.map.markers[i] != null){
				 img = App.jsonData.map.markers[i].Property.Images[0].ImageUrl;
				 addr = App.jsonData.map.markers[i].address;
				 //	 		 alert(i + ". " + addr + ": " + img);
			}
		 }
		}
	
		}
	},

	renderMarkers: function() {
	    // Clear overlay
	    this.gMap.clearOverlays();

		// Hide loading image
		document.getElementById('sidebarLoading').style.display = "none";

		// Remove old sidebar
		try
		{
			document.getElementById("sideBar").removeChild(this.Table);
		}
		catch (e) {}

	    // Empty table
		this.Table = document.createElement("table");
		this.Table.className="General";
		this.Table.cellPadding="0";
		this.Table.cellSpacing="0";
		this.Table.width="100%";
		this.TBody = document.createElement('tbody');
		this.Table.appendChild(this.TBody);

		var marker = null;
		
		for (var i=0; i<this.jsonData.map.markers.length; i++) {
			// Is marker visible?
			if (!this.jsonData.map.markers[i].visible){
				continue;
			}else{

			// obtain the attribues of each marker
			lat = parseFloat(this.jsonData.map.markers[i].lat);
			lng = parseFloat(this.jsonData.map.markers[i].lng);
			point = new GLatLng(lat,lng);
			this.isValue = true;
			marker = this.createMarker(i, point);

			//Show information for the 1st marker - trigger onclick event. We need to have an ID
			if (i == 0)
			{
				this.activeMarkerID = marker.id;	
			}
			}

		}

		// put the assembled sideBarHtml contents into the sideBar div
		document.getElementById("sideBar").appendChild(this.Table);

		if (this.activeMarkerID != null && this.scrollSidebar && this.isValue)
		{
			try
			{
				/* Scroll workaround: scrollIntoView(true) scrolls entire window to a bottom */
				document.getElementById('row_' +  this.activeMarkerID).scrollIntoView(false);
				this.onMarkerClick(this.activeMarkerID);
			}
			catch(e)
			{
				// nothing
			}
		}
		else{
			document.getElementById('propertyInfoNo').style.display = 'block';
			document.getElementById('propertyInfo').style.display = 'none';
		  
			// Hide information box
			document.getElementById('dFeatures').style.display = 'none';
			// Show downloading message 
			document.getElementById('propertyInfoLoading').style.display = 'none';
		}

		//Show information for the 1st marker - trigger onclick event
		//GEvent.trigger(marker2, 'click', this);

	},

	// A function to create the marker and set up the event window
	createMarker: function(id, point) {
		
		// Active record
		var actRecord = this.jsonData.map.markers[id];

		// Standard icon
		var markerOptions = {}; 
		// Set icon
		try 
		{
			markerOptions.icon = this.gIcons[actRecord.iconname]; 
		}
		catch (e)
		{
			markerOptions.icon = new GIcon(G_DEFAULT_ICON);
		    /*
			markerOptions.icon.image = "http://www.homeexploring.com/maps/img/icons/house-green.png";
			markerOptions.icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
			markerOptions.icon.iconSize = new GSize(15, 22);
			markerOptions.icon.shadowSize = new GSize(10, 15);
			*/
		}
		
		// Instatiate new Gmarker
		var marker = new GMarker(point, markerOptions);

		// Set marker id
		marker.id =  id;
		
		// build tootip
		// Optimization: lets byuild tooltip only when we need it
		//opt var tootip = actRecord.address;

		// *************** store the name so that the tooltip function can use it ************
		//opt marker.tooltip = '<div class="tooltip">'+tootip+'</div>';
		
		GEvent.addListener(marker, "click", function() {
			this.onMarkerClick(id);
		}.bind(this));

		this.gmarkers[id] = marker;

		
		// ***************** Create Sidebar Rows ************************
		var tr	= document.createElement('tr');
		tr.id = "row_" + id;
		//Cell 1 - (checkbox? ) and image 
		var td = document.createElement('td');
		if (this.cma)
		{
	        //tmpHtml += '<td><input id="Check'+MAPBUILDER.widget.MapObject.Ref.markers[i].Property.ID+'" type="checkbox" name="Cmp" value="1" onclick="ProcessProperty('+i+', this)"></td><td><img src="' + MAPBUILDER.widget.MapObject.Ref.markers[i].link + '"></td><td align="right">' + MAPBUILDER.widget.MapObject.Ref.markers[i].Property.Currency;
			var include	= document.createElement('input');
			include.id = id;
			//include.id = 'CheckBox' + actRecord.Property.ID;
			include.type = "checkbox";
			include.value = "1";

			td.appendChild(include);
			tr.appendChild(td);
		}
		//
		
		td = document.createElement('td');
		var img = document.createElement('img');
		/* **********Temp code************* */
		/*var imgscr = markerOptions.icon.image;
		imgscr = imgscr.split("ing/");
		//alert("imgscr " + imgscr[1]);
		img.src = "http://192.168.10.152/homeexploring.com/" + imgscr[1];*/
		/**/
		
		
		img.src = markerOptions.icon.image;
		
		td.appendChild(img);
		tr.appendChild(td);
		
		//Cell 2 - price
		td = document.createElement('td');
		td.appendChild(document.createTextNode('$'+actRecord.Property.FormatedPrice));
		tr.appendChild(td);
		
		//Cell 3, contains link
		td = document.createElement('td');
		var a = document.createElement('a');
		// Set custom attribute(unique id) to identify an element
		a.id = id;
		a.href = "javascript: void(null)";
		a.appendChild(document.createTextNode(actRecord.address));
		td.appendChild(a);
		tr.appendChild(td);

		//Append this TR to the TBody
		this.TBody.appendChild(tr);

		// Add overley to a marker
		this.gMap.addOverlay(marker);

		// *********** The new marker "mouseover" and "mouseout" listeners ***********
		GEvent.addListener(marker,"mouseover", function() {
			this.showTooltip(marker);
			// Change active sidebar row background color

			// removed scroll sidebar - KJ 10/8

		}.bind(this));
		   
		GEvent.addListener(marker,"mouseout", function() {
			this.tooltip.style.visibility="hidden";
			// Change active sidebar row background color back to white for non active marker
			if (this.activeMarkerID != id)
			{
				document.getElementById('row_'+ id).style.backgroundColor = "#FFF";
			}

		}.bind(this));

     	// Finally return marker
     	return marker; 
	},


	// A function to create the marker and set up the event window
	buildIcons: function() {
		var oTimer = new Util.Timer();
		var icons = this.jsonData.map.icons;

		var appIcon = null;
		var name = null;
		var x = null;
		var y = null;

		for (var i = 0; i < icons.length ; i++)
		{

			// Required: icon name
			name = icons[i].name;		

			// Test Variable
			x = "" ;				
			// Test Variable
			y = "" ;				

			// Check for an icon copy
			x = icons[i].copy;

			// Make sure icon to copy has been built
			if (x && gicons[x])			
			{
				appIcon = new GIcon(gicons[x]);
			} 
			else
			{
				appIcon = new GIcon();
			}

			// Required: Icon Image
			appIcon.image = icons[i].image.src;	

			x = "" ;
			y = "" ;
			// Check for an icon anchor
			x = icons[i].xanchor;
			y = icons[i].yanchor;

			if (x != null && y!= null && x && y)
			{
				appIcon.iconAnchor = new GPoint(parseInt(x),parseInt(y));
			}

			x = "" ;
			y = "" ;

			// Check for an icon infowindow anchor
			x = icons[i].xiwanchor;
			y = icons[i].yiwanchor;

			if (x != null && y!= null && x && y)
			{
				appIcon.infoWindowAnchor = new GPoint(parseInt(x),parseInt(y));
			}

			x = "" ;
			y = "" ;
			// Check for icon image height and width
			x = icons[i].image.width;
			y = icons[i].image.height;

			if (x != null && y!= null && x && y)
			{
				appIcon.iconSize = new GSize(parseInt(x),parseInt(y));
			}

			x = "" ;
			// Check for an shadow image
			x = icons[i].shadow.src;

			if (x != null && x)
			{
				appIcon.shadow = x ;
			}

			x = "" ;
			y = "" ;
			// Check for an icon shadow dimension
			x = icons[i].shadow.width;
			y = icons[i].shadow.height;

			if (x != null && y!= null && x && y)
			{
				appIcon.shadowSize = new GSize(parseInt(x),parseInt(y));
			}
      
			this.gIcons[name] = appIcon;

		}

		if (this.debug) this.LogWriter.log(oTimer.Tick(1, "Icons building finished in "), "time");
	},

	loadMap: function()
	{
		if (this.gMap == null)
		{
			this.gMap = new GMap2(document.getElementById("map")); 

			/* Insert MapBuilder Logo */
			var info=document.createElement('div');
			info.id='MapBuilderInfo';
			info.style.position='absolute';
			info.style.right='1px';
			info.style.bottom='25px';
			info.style.backgroundColor='transparent';
			info.style.zIndex=25500;
			info.innerHTML='<a id="CreatedByMapBuilder" href="http://www.mapbuilder.net"><img src="http://mapbuilder.net/img/mo24.gif" alt="Powered By MapBuilder.net" style="border:0; margin: 2px;"/></a>';
			this.gMap.getContainer().appendChild(info);
		}
	},

	// Event handler
	sideBarOnClick: function(e)
	{
		//if (this.debug) this.LogWriter.log('sideBarOnClick', 'information');
		var el = Event.element(e);
		// Run event for a checkbox
		if (el.nodeName == "INPUT") 
		{
			ProcessProperty(el.getAttribute("id"), el);
		}    

		if (el.nodeName != "A")  return;

		id = el.getAttribute("id");
		this.onMarkerClick(id, true);
	},

	// Event handler
	sideBarOnMouseOver: function(e)
	{
		//if (this.debug) this.LogWriter.log('sideBarOnMouseOver', 'information');
		var el = Event.element(e);
		if (el.nodeName != "A")  return;
		
		id = el.getAttribute("id");

		// Change active sidebar row background color
		if (this.activeMarkerID != id)
		{
			document.getElementById('row_'+ id).style.backgroundColor = this.sideBarRowOver;
		}

		// Show tootip
		this.showTooltip(this.gmarkers[id])

		if (this.flipMarkers)
		{
			// Create new marker with ACTIVE icon.
			// We'll use the same icon with bigger size
			var markerOptions2 = {}; 
			markerOptions2.icon = new GIcon(this.gmarkers[id].getIcon()); 
			//markerOptions2.icon.image = "http://www.homeexploring.com/maps/img/icons/house-red.png";
			markerOptions2.icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
			markerOptions2.icon.iconSize = new GSize(20, 34);
			markerOptions2.icon.shadowSize = new GSize(37, 34);
			this.activeMarker = new GMarker(this.gmarkers[id].getPoint(), markerOptions2);

			this.gMap.removeOverlay(this.gmarkers[id]);
			this.gMap.addOverlay(this.activeMarker);
		}
	},

	// Event handler
	sideBarOnMouseOut: function(e)
	{
		//if (this.debug) this.LogWriter.log('sideBarOnMouseOut', 'information');
		var el = Event.element(e);
		if (el.nodeName != "A")  return;

		id = el.getAttribute("id")

		// Change active sidebar row background color back to white for non active marker
		if (this.activeMarkerID != id)
		{
			document.getElementById('row_'+ id).style.backgroundColor = "#FFF";
		}

		// Remove tootip
		this.tooltip.style.visibility="hidden"

		// Do we change icon
		if (this.flipMarkers)
		{

			if (this.activeMarker != null)
				this.gMap.removeOverlay(this.activeMarker);
			this.gMap.addOverlay(this.gmarkers[id]);

			// The new marker "mouseover" and "mouseout" listeners
			GEvent.addListener(this.gmarkers[id],"mouseover", function() {
				this.showTooltip(this.gmarkers[id]);
			}.bind(this));
			       
			GEvent.addListener(this.gmarkers[id],"mouseout", function() {
				this.tooltip.style.visibility="hidden"
			}.bind(this));        
		}
	},

	// ***************** This function displays the tooltip *****************
	// it can be called from an icon mousover or a sideBar mouseover
	showTooltip: function(marker) {
		//if (this.debug) this.LogWriter.log("showTooltip start", "info");

		// Active record
		var actRecord = this.jsonData.map.markers[marker.id];

		//Create Images
		var imgTag = '';
		var oDate=new Date();
		for (var i = 0; i < actRecord.Property.Images.length; i++)
		{
			if (i==0)
			{ 
				// Do not sent NC(No Cache) parameter imgTag = '<img width="150" src="' + this.imgURL + actRecord.Property.Images[i].ImageUrl + "?NC=" + oDate.getTime() + '" border="0" style="width:150px; height:112px; overflow:truncate;" alt="Property Image"/>';
				imgTag = '<img width="150" src="' + this.imgURL + actRecord.Property.Images[i].ImageUrl + '" border="0" style="width:150px; height:112px; overflow:truncate;" alt="Property Image"/>';
				break;
			}
		}

		//Remove previous tooltip
		try
		{
			this.tooltip.removeChild(this.tooltipTable); 
		}
		catch(e) {}

		/* DHTML Table tooltip doesn't work in IE properly
		//Build tooltip table
		this.tooltipTable = document.createElement("table");
		this.tooltipTable.setAttribute('class', 'tooltipTable');
		this.tooltipTable.cellPadding="0";
		this.tooltipTable.cellSpacing="0";

		// Row 1
		var tr	= document.createElement('tr');
		//Cell 1
		var td = document.createElement('td');
		td.innerHTML = imgTag;
		tr.appendChild(td);

		//Cell 1
		var td = document.createElement('td');
		td.appendChild(document.createTextNode(actRecord.address));
		tr.appendChild(td);
		
		//
		this.tooltipTable.appendChild(tr);
		
		this.tooltip.appendChild(this.tooltipTable); 
		*/

		
		this.tooltip.innerHTML = 
			'<table border="0" cellpadding="0" class="tooltipTable">'+
			'<tr valign="top">'+
				'<td>' + imgTag + '</td>'+
				'<td>' +
				((actRecord.Property.Status=='Sold') ? ('Sold </br>' + actRecord.Property.SoldDate + '<br/>') : '') + 
				'Bed: ' + actRecord.Property.Bedrooms + '<br />' + 
				'Bath: ' + actRecord.Property.Bathrooms + '<br />' + 
				((actRecord.Property.Status=='Sold') ? ('MDC: ' + actRecord.Property.mdc) : ('DOM: ' + actRecord.Property.dom))+
				'</td>'+
			'</tr>'+
			'<tr>'+
				'<td>' + actRecord.address + '</td>'+
				'<td>$' + ((actRecord.Property.Status=='Sold') ? actRecord.Property.SoldPrice : Util.formatNumber(actRecord.Property.Price)) + '</td>'+
			'</tr>'+
			'</table>';


		var price =  ((actRecord.Property.Status=='Sold') ? actRecord.Property.SoldPrice : Util.formatNumber(actRecord.Property.Price));
		var str='';
		str+='<div id="containerToolTip"> ';
		str+='	';
		str+='		<div class="abs01" style="top: 2px; left: 2px; width: 150px; height: 112px; background-color: #fff;">';
		//str+='			' + imgTag;
		str+='			<span id="TooltipImage" ></span>' ;
		str+='		<\/div>';
		str+='	';
		str+='	 	<div  style="POSITION: relative; left: 160px; top: 10px; width: 110px; height: 100px; backgrouond-color: #fff;">  	';
		str+='			<table border="0" bordercolor="#dcc9a7" cellpadding="2" cellspacing="0" width="100%">';
		str+='			<tbody>';
		str+='				<tr><td>' +
			((actRecord.Property.Status=='Sold') ? 'SOLD:' : 'Listed:') + 
			'<\/td><td>' +
			((actRecord.Property.Status=='Sold') ? actRecord.Property.SoldDate : actRecord.Property.ListDate) + 		
			'<\/td><\/tr>';

		str+='				<tr><td colspan="2"> <\/td><\/tr>';
		str+='				<tr><td style="padding-top: 5px;">Bed<\/td><td>' + actRecord.Property.Bedrooms + '<\/td><\/tr>';
		str+='				<tr><td>Bath<\/td><td>' + actRecord.Property.Bathrooms + '<\/td><\/tr>';
		if(actRecord.Property.Status=='Sold'){
			str+='				<tr><td>MDC<\/td><td>' + actRecord.Property.mdc +'<\/td><\/tr>';
		}else{
			str+='				<tr><td>DOM<\/td><td>' + actRecord.Property.dom +'<\/td><\/tr>';
		}
		str+='				<tr><td colspan="2"> <\/td><\/tr>';
		str+='				<tr><td colspan="2" style="padding-top: 5px;">$ ' + price + '<\/td><\/tr>';
		str+='			<\/tbody><\/table>';
		str+='			';
		str+='		<\/div>';
		str+='		';
		str+='		<div class="abs01" style="top: 116px; left: 1px; height: 30px; width: 276px; background-color: #fff;">';
		str+='			<table border="0" bordercolor="#dcc9a7" >';
		str+='				<tbody>';
		str+='				<tr><td><IMG SRC="' + this.gIcons[actRecord.iconname].image + '" border="0" float="left"><\/td><td>' + actRecord.address + '<\/td><\/tr>';
		str+='			';
		str+='			<\/tbody>';
		str+='			<\/table>';
		str+='		<\/div>';
		str+='	';
		str+='<\/div>';
		this.tooltip.innerHTML = str;

		for (var i = 0; i < actRecord.Property.Images.length; i++)
		{
			if (i==0)
			{ 
				/* Image Processing */
				var currentimg = new Image();
				if(actRecord.Property.Images[i].ImageUrl == "NoPhoto.gif"){
					currentimg.src = "http://www.homeexploring.com/P_pictures/" + actRecord.Property.Images[i].ImageUrl;
				}else if(actRecord.Property.Images[i].ImageUrl == "NoPhoto.jpg"){
					currentimg.src = "http://www.homeexploring.com/P_pictures/" + actRecord.Property.Images[i].ImageUrl;
				}else{
					currentimg.src = this.imgURL + actRecord.Property.Images[i].ImageUrl;
				}
				currentimg.title = 'Property Image';
				currentimg.id = "TooltipImage";
				currentimg.width = 150;
				currentimg.className = 'TooltipImage';
				var current = currentimg;

				var img =  document.getElementById("TooltipImage");

				var imgNode = document.createElement("IMG");
				imgNode.setAttribute("src",current.src);
				imgNode.setAttribute("title",current.title);
				imgNode.setAttribute("width",150);
				imgNode.setAttribute("id",current.id);

				//img.parentNode.replaceChild((this.browser == "safari" ? imgNode : current), img);
				img.parentNode.replaceChild(current, img);
				break;
			}
		}


		var point = this.gMap.getCurrentMapType().getProjection().fromLatLngToPixel(this.gMap.fromDivPixelToLatLng(new GPoint(0,0),true),this.gMap.getZoom());
		var offset = this.gMap.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),this.gMap.getZoom());
		var anchor = marker.getIcon().iconAnchor;
		var iconW = marker.getIcon().iconSize.width;
		var iconH = marker.getIcon().iconSize.height;

		// Get tooltip width using PrototypeLib
		var oTTDim = Element.getDimensions(this.tooltip);
		// -- or --
		// use simple DOM methods
		/*
		var oTTDim = {}
		oTTDim.width = this.tooltip.clientWidth; 
		oTTDim.height = this.tooltip.clientHeight; 
		*/

		// Map size in pixels
		// Useless var oMapSize = this.gMap.getSize();
		var maxOffset_NE = this.gMap.getCurrentMapType().getProjection().fromLatLngToPixel(this.gMap.getBounds().getNorthEast(), this.gMap.getZoom());
		var maxOffset_SW = this.gMap.getCurrentMapType().getProjection().fromLatLngToPixel(this.gMap.getBounds().getSouthWest(), this.gMap.getZoom());
		var ttOffset = this.gMap.getCurrentMapType().getProjection().fromLatLngToPixel(this.gMap.fromDivPixelToLatLng(new GPoint(oTTDim.width, oTTDim.height),true),this.gMap.getZoom());

		/* 
		* Can you set the max top position of the mouseover box to be below the map/satellite/hybrid buttons so mouse image does not go behind buttons?
		*/
		maxOffset_NE.y = maxOffset_NE.y + 40;



		// Display left side tooltip
		if (maxOffset_NE.x - offset.x  <  0) {
			posX = maxOffset_NE.x - point.x - anchor.x - oTTDim.width;
		} else if (maxOffset_NE.x - offset.x  <  oTTDim.width) {
			posX = offset.x - point.x - anchor.x - oTTDim.width;
		} else if (maxOffset_NE.x - offset.x  > 530) {
			posX = maxOffset_SW.x - point.x - anchor.x + iconW;
		} else {
			posX = offset.x - point.x - anchor.x + iconW;
		}

		// offset.y - maxOffset_NE.y === actual Y marker's coordinate relative to the NORTH map border 
		if (offset.y - maxOffset_NE.y - oTTDim.height < 0) {
			posY = offset.y - point.y - anchor.y /* + iconH */;
		}	else {
			posY = offset.y - point.y - anchor.y /* - iconH */ - oTTDim.height;
		}

		if (this.debug) 
		{
			var logMsg = "";
			logMsg +=  " oTTDim.height:  " +  oTTDim.height + " oTTDim.width: " + oTTDim.width;
			logMsg +=  " maxOffset_NE.x:  " +  maxOffset_NE.x + " maxOffset_NE.y: " + maxOffset_NE.y;
			logMsg +=  " maxOffset_SW.x:  " +  maxOffset_SW.x + " maxOffset_SW.y: " + maxOffset_SW.y;
			logMsg +=  " offset.x: " + offset.x + " point.x: " + point.x + " anchor.x: " + anchor.x;
			logMsg +=  " offset.y: " + offset.y + " point.y: " + point.y + " anchor.y: " + anchor.y;
			logMsg +=  " COND X: " + (maxOffset_NE.x - offset.x ) + " < " + oTTDim.width;
			logMsg +=  " COND Y: " + (offset.y - maxOffset_NE.y - oTTDim.height) + "< 0";
			logMsg +=  " pos: (" + posX + ", " + posY + ")";
		}

		var pos  =  new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(posX, posY)); 
		
		if (this.debug) this.LogWriter.log(logMsg, "info");

		pos.apply(this.tooltip);
		this.tooltip.style.visibility = "visible";

		//if (this.debug) this.LogWriter.log("showTooltip end", "info");

	},

	// Search
	doSearch: function()
	{
		var oTimer = new Util.Timer();
		
		//Remove image and images on Image panel
		document.getElementById('propertyInfo').style.display = 'none';
		// Hide property information box 
		document.getElementById('dFeatures').style.display = 'none';

		// Update status bar
		document.getElementById('statusBar').innerHTML = 'Searching...';
    
		// Get celection criteria 
		// Status 
		var isActive = true;
		var isSold = false;
		var isAll = false;
		switch (document.getElementById('F').PropStatus.value)
		{
			case 'Active':
				isActive = true;
				isSold = false;
				isAll = false;
				break;
			case 'Sold':
				isActive = false;
				isSold = true;
				isAll = false;
				break;
			case 'All':
				isActive = false;
				isSold = false;
				isAll = true;
				break;
		}

		// Type
		var isHouse = false;
		var isCondo = false;
		var isAny = true;
		switch (document.getElementById('F').PropType.value)
		{
			case 'House':
				isHouse = true;
				isCondo = false;
				isAny = false;
				break;
			case 'Condo':
				isHouse = false;
				isCondo = true;
				isAny = false;
				break;
			case 'All':
				isHouse = false;
				isCondo = false;
				isAny = true;
				break;
		}
    
		// Price
		var sSearchPrice = Util.getRadioValue(document.getElementById('F').SearchPrice);
		var neighborhood = document.getElementById('neighborhood').value;
		var intMinPrice = 0;
		var intMaxPrice = 0;

		// Price range
		if (neighborhood == 'Oceanfront' || neighborhood == 'Montecito') {
            if (neighborhood == 'Oceanfront' && isCondo == true){
    		    switch (sSearchPrice)
			    {
			    case 'All':
			        intMinPrice = 0;
			        intMaxPrice = 9999999999;
			        break;
			    case '0':
			        intMinPrice = 0;
				    intMaxPrice = 2000000;
//			    intMaxPrice = 2000000;
			        break;
			    case '1':
			        intMinPrice = 2000000.01;
			        intMaxPrice = 4000000;
//			    intMinPrice = 2000000.01;
//			    intMaxPrice = 3500000;
			        break;
			    case '2':
			        intMinPrice = 4000000.01;
//			    intMinPrice = 3500000.01;
			        intMaxPrice = 9999999999;
			        break;
			    }
			}
			else{
    		    switch (sSearchPrice)
			    {
			    case 'All':
			        intMinPrice = 0;
			        intMaxPrice = 9999999999;
			        break;
			    case '0':
			        intMinPrice = 0;
				    intMaxPrice = 2500000;
//			    intMaxPrice = 2000000;
			        break;
			    case '1':
			        intMinPrice = 2500000.01;
			        intMaxPrice = 5000000;
//			    intMinPrice = 2000000.01;
//			    intMaxPrice = 3500000;
			        break;
			    case '2':
			        intMinPrice = 5000000.01;
//			    intMinPrice = 3500000.01;
			        intMaxPrice = 9999999999;
			        break;
			    }
			}
		} else {
		    switch (sSearchPrice)
		    {
			case 'All':
				intMinPrice = 0;
//				intMaxPrice = 200000000;
				intMaxPrice= 9999999999;
				break;
			case '0':
				intMinPrice = 0;
				intMaxPrice = 1200000;
//				intMaxPrice = 2500000;
				break;
			case '1':
//				intMinPrice = 2500000.01;
//				intMaxPrice = 5000000;
				intMinPrice = 1200000.01;
				intMaxPrice = 1500000;
				break;
//			case '2':
//				intMinPrice = 5000000.01;
//				intMaxPrice = 9999999999;
//				break;
			case '2':
				intMinPrice = 1500000.01;
				intMaxPrice = 2000000;
				break;
			case '3':
				intMinPrice = 2000000.01;
				intMaxPrice = 9999999999;
			break;
		    }
		}

		//alert ("Price: "+ intMinPrice+"..."+intMaxPrice+", Bed"+sSearchPrice+", Bath:"+fMinBathrooms);
		var price, bedrooms, bathrooms;
		var nFound = 0;
		// Loop through markers
		for (var i = 0; i < this.jsonData.map.markers.length ; i++)
		{
			// Set link
			try					
			{
				this.jsonData.map.markers[i].visible = true;
        
				price = Util.toInt(this.jsonData.map.markers[i].Property.Price); 

				// First, filter price
				if (price < intMinPrice)
				{ 
					this.jsonData.map.markers[i].visible = false;
					continue;
				}
				if (intMaxPrice > 0 && price > intMaxPrice)
				{ 
					this.jsonData.map.markers[i].visible = false;
					continue;
				}

				//setStatus(isAll, isActive, isSold, this.jsonData.map.markers[i]);
				
				// Move down to check type
				if (!isAny)
				{					
					if(this.jsonData.map.markers[i].Property.Type=='Others'){
						this.jsonData.map.markers[i].visible = false;
						continue;
					}
					if (!isHouse && this.jsonData.map.markers[i].Property.Type=='House')
					{ 
						this.jsonData.map.markers[i].visible = false;
						continue;
					}
					if (!isCondo && (this.jsonData.map.markers[i].Property.Type=='Condo'))
					{ 
						this.jsonData.map.markers[i].visible = false;
						continue;
					}
				}
		
				// Set active marker
				
				if (!isAll)
				{
					if (!isActive && this.jsonData.map.markers[i].Property.Status=='Active')
					{ 
						this.jsonData.map.markers[i].visible = false;
						continue;
					}
					if (!isSold && (this.jsonData.map.markers[i].Property.Status=='Sold'))
					{ 
						this.jsonData.map.markers[i].visible = false;
						continue;
					}
				}
				
				
				// Show first available location anyway 
				// if (this.activeMarkerID == null || this.activeMarkerID == 0)
				if (nFound == 0)
					this.activeMarkerID = i;

				// Done with filtering
				nFound ++;
			} 
			catch (e) { }
		} // for

		// Add status bar information
		document.getElementById('statusBar').innerHTML = nFound + ' locations found.';

		// And finally re-render markers
		this.renderMarkers();

		if (this.debug) this.LogWriter.log(oTimer.Tick(1, "Search finished in "), "time");
		
	},
	
	searchOptions: function() {
	    var s = document.getElementById('search_options');
	    var a = '';
//	    if (this.neighborhood == 'HopeRanch' || this.neighborhood == 'Montecito') {
	    if (this.neighborhood == 'Oceanfront' || this.neighborhood == 'Montecito') {
            if (this.neighborhood == 'Oceanfront' && this.currentSearchType == 'Condo'){
		        a += "<input id='SearchPrice0' name='SearchPrice' value='0' type='radio' onclick='App.doSearch();' /><label for='SearchPrice0'>&lt;2.0M</label>";
		        a += "<input id='SearchPrice1' name='SearchPrice' value='1' type='radio' onclick='App.doSearch();' /><label for='SearchPrice1'>2.0-4.0M</label>";
		        a += "<input id='SearchPrice2' name='SearchPrice' value='2' type='radio' onclick='App.doSearch();' /><label for='SearchPrice2'>&gt;4.0M</label>";
		        a += "<input id='SearchPrice3' name='SearchPrice' value='All' checked='checked' type='radio' onclick='App.doSearch();' /><label for='SearchPrice4'>All</label>";
			}
			else{
		        a += "<input id='SearchPrice0' name='SearchPrice' value='0' type='radio' onclick='App.doSearch();' /><label for='SearchPrice0'>&lt;2.5M</label>";
		        a += "<input id='SearchPrice1' name='SearchPrice' value='1' type='radio' onclick='App.doSearch();' /><label for='SearchPrice1'>2.5-5.0M</label>";
		        a += "<input id='SearchPrice2' name='SearchPrice' value='2' type='radio' onclick='App.doSearch();' /><label for='SearchPrice2'>&gt;5.0M</label>";
		        a += "<input id='SearchPrice3' name='SearchPrice' value='All' checked='checked' type='radio' onclick='App.doSearch();' /><label for='SearchPrice4'>All</label>";
            }
	    } else {
		    a += "<input id='SearchPrice0' name='SearchPrice' value='0' type='radio' onclick='App.doSearch();' /><label for='SearchPrice0'>&lt;1.2M</label>";
		    a += "<input id='SearchPrice1' name='SearchPrice' value='1' type='radio' onclick='App.doSearch();' /><label for='SearchPrice1'>1.2-1.5M</label>";
		    a += "<input id='SearchPrice2' name='SearchPrice' value='2' type='radio' onclick='App.doSearch();' /><label for='SearchPrice2'>1.5-2.0M</label>";
		    a += "<input id='SearchPrice3' name='SearchPrice' value='3' type='radio' onclick='App.doSearch();' /><label for='SearchPrice3'>&gt;2.0M</label>";
		    a += "<input id='SearchPrice4' name='SearchPrice' value='All' checked='checked' type='radio' onclick='App.doSearch();' /><label for='SearchPrice4'>All</label>";
	    }
		s.innerHTML = a;
	},

	// This functions starts when user click on a marker
	onMarkerClick: function(id, is_sidebar_click)
	{
		if(this.isValue){
		//Remove old active marker if available
		try 
		{
			document.getElementById('row_'+ this.activeMarkerID).style.backgroundColor = "#FFF";
		}
		catch (e) {} 

		// Change active sidebar row background color
		try 
		{
			document.getElementById('row_'+ id).style.backgroundColor = this.sideBarRowActive;
		}
		catch (e) {} 

		this.activeMarkerID = id;

        // And now, download all information for the selected marker using JSON call
        if (this.debug) this.LogWriter.log("Going to download PROPERTY data ...");

		// Build Images
		var Property = null;
		try{
			Property = this.jsonData.map.markers[id].Property;
		}
		catch (e)
		{
			// Do nothing
			return;
		}

		//Remove image and images on Image panel
		document.getElementById('dImg').innerHTML =  ''; 
      if(Property != null){
		// And Finally make panel visible and hide NoInfo panel
		document.getElementById('propertyInfoNo').style.display = 'none';
		document.getElementById('propertyInfo').style.display = 'block';
      
		// Hide information box
		document.getElementById('dFeatures').style.display = 'none';
        // Show downloading message 
		document.getElementById('propertyInfoLoading').style.display = 'block';
	  }else{
		  document.getElementById('propertyInfoNo').style.display = 'block';
		document.getElementById('propertyInfo').style.display = 'none';
      
		// Hide information box
		document.getElementById('dFeatures').style.display = 'none';
        // Show downloading message 
		document.getElementById('propertyInfoLoading').style.display = 'none';
	  }
		// Scroll sidebar table to show record for a selected tooltip
		if (this.scrollSidebar && !is_sidebar_click)
		{
				/* Scroll workaround: scrollIntoView(true) scrolls entire window to a bottom */
				/* Use scrollTop instead of scrollIntoView to fix page autoscrolling
				 * document.getElementById('row_' +  marker.id).scrollIntoView(false);
				 */
				var row_el = document.getElementById('row_'+ id);
				// Get row position
				var rowPos = Position.cumulativeOffset(row_el);
				var tablePos = Position.cumulativeOffset(this.TBody);
				var c = document.getElementById("sideBar");
				c.scrollTop = rowPos[1] - tablePos[1] - 30; /* use 30px delta */ 
				
				// KJ 10/12 - deleted b/c causing error that "marker not defined"
				// Change active sidebar row background color
				//if (this.activeMarkerID != marker.id)
				//{
				//		row_el.style.backgroundColor = this.sideBarRowOver;
				//}
		}

		if (Property != null)
		{

			//DEV GDownloadUrl("../data/PropertyJSON_gz.js", this.showLocationInfo.bind(this));
			GDownloadUrl(this.PropertyFeed + "?ID="+Property.ID, this.showLocationInfo.bind(this));

			var images = Property.Images;
			if (images[0] != undefined) addBigImgNew('dImg', this.imgURL + images[0].ImageUrl); else addImg('dImg', '');

			var currentimg = [];
			var current = [];
			var img = []; 

			// Remove all images
			for (i=0; i<6; i++)
			{
				img[i] =  document.getElementById('dImg' + i);

				var spanNode = document.createElement("span");
				spanNode.setAttribute("id",'dImg' + i);

				img[i].parentNode.replaceChild(spanNode, img[i]);
			}

			// Show small images if we have more than 1 image
			if (images.length > 1)
			{
				for (i=0; i< ((images.length> 6) ? 6 : images.length); i++)
				{
					//this is ugly hack to resolve images caching problem in IE
					setTimeout("buildImage("+i+", '" + this.imgURL + images[i].ImageUrl + "')", 100);
				}
			}
		}
		else{
			document.getElementById('propertyInfoNo').style.display = 'block';
			document.getElementById('propertyInfo').style.display = 'none';			
			document.getElementById('propertyInfoLoading').style.display = 'none';
			document.getElementById('dFeatures').style.display = 'none';
		}
		}else{
			document.getElementById('propertyInfoNo').style.display = 'block';
			document.getElementById('propertyInfo').style.display = 'none';			
			document.getElementById('propertyInfoLoading').style.display = 'none';
			document.getElementById('dFeatures').style.display = 'none';
		}
	},

	//Show proprty information 
	showLocationInfo: function(doc) 
	{
        if (this.debug) this.LogWriter.log("PROPERTY data downloaded");

		// Parse the JSON document
        var jsonLocationData = eval('(' + doc + ')');
		
		var Property = jsonLocationData.Property;
		if(Property != null){
		// Show/hide condo info
		document.getElementById('CondoInfo').style.display = (Property.Type == "Condo") ? 'block' : 'none';
		
		// ADD BR to an address: Property Detail title: center text and put a line break between property street address and city/state/zip
		//$sAddress = $aLocation['Address'] . "<br/> " . $aLocation['City'] . ", " . $aLocation['State'] . " " . $aLocation['Zip'];

		setText("dAddress", jsonLocationData.address + "<br>" + jsonLocationData.city + ", " + jsonLocationData.state + " " + jsonLocationData.zip);
		
		if(Property.STATUS == 'Sold'){
			setText("dPropertyPrice", "Sold Price: " + ((Property.SP == 'N/A') ? Property.SP : ('$' + Property.SP)));
		}else{
			setText("dPropertyPrice", "Listing Price: " + ((Property.LP == 'N/A') ? Property.LP : ('$' + Property.LP)));
		}
		
		if(Property.STATUS == 'Sold'){
			setText("dPropertyDate", "Sold Date: " + Property.SD);
		}else{
			setText("dPropertyDate", "List Date: " + Property.LD);
		}
		//setText("dListingPrice", (Property.LP == 'N/A') ? Property.LP : ('$' + Property.LP));
		
		
		//setText("dPriceRatio", Property.PR);
		if(Property.STATUS == 'Sold'){
		setText("dDom", "Marketing Days to Close: " + Property.MDC);
			
			//setText("dDom", "Marketing Days to Close: " + );
		}else{
			setText("dDom", "Days on Market: " + Property.DOM);
		}
		setText("dPType", Property.PTYPE);
		setText("dTotal_BR", Property.BR);
		setText("dTotal_BA", Property.BA);
		setText("dYr_Built", Property.BU);
		setText("dTotal_Sqft", Property.TSQ);
		//setText("dsLot_acres", Property.ACR);
		//setText("dCondition", Property.CO);
		setText("dTotalUnits", Property.UN);
		setText("dAssociation_fee", Property.AF);
		setText("dAssociation_name", ((Property.DevName == null) ? '' : Property.DevName));
		setText("dRemarks", (Property.RE == null) ? "" : Property.RE);

        // Hide downloading message 
		document.getElementById('propertyInfoLoading').style.display = 'none';
		// Show information
		document.getElementById('dFeatures').style.display = 'block';
		}
		else{
			document.getElementById('propertyInfoNo').style.display = 'block';
			document.getElementById('propertyInfo').style.display = 'none';			
			document.getElementById('propertyInfoLoading').style.display = 'none';
			document.getElementById('dFeatures').style.display = 'none';
		}
	},
	
	
	/**
	* Geocode given address re-center map
	* @param	{String}	location	Location address
	*/
	addrSearch: function(location) 
	{


		// Build the Yahoo! web services call
		request = 'http://mapbuilder.net/Service/geocode.yahoo.php?appid=mapobject.net&location=' + location  + '&output=json&callback=App.addrSearchShow';
		// Create a new script object
		var oLoader = new Util.JSLoader(request);
		// Build the script tag
		oLoader.buildScriptTag();
		// Execute (add) the script tag
		oLoader.addScriptTag();
		
	},

	/**
	* This is address search/geocoding callback function.
	* This is the callback function that is specified in the request url and gets executed after the data is returned 
	* by Yahoo! Geocoding API http://developer.yahoo.com/maps/rest/V1/geocode.html.
	* @param	{JavaScript}	jData Geocoding results
	*/
	addrSearchShow: function(jData) 
	{
		// Parse the JSON document
		if (jData == null)
		{
			alert("There was a problem parsing search results.");
			return;
		}

		//get the values out of the object
		var lat = jData.ResultSet.Result[0].Latitude;
		var lon = jData.ResultSet.Result[0].Longitude;
		this.gMap.setCenter(new GLatLng(lat, lon), 15);
	}
	/////////////////////////////////////////////////////////////////////////
	// EOF Geocode given address re-center map
	/////////////////////////////////////////////////////////////////////////


}
App.load();


/* *********************************************************************************
* Helper functions.
* *********************************************************************************/

function buildAddrStr (a, c, z, s, co)
{
	var addr = (a == '') ? '' : (a + '<br />');
	addr = (addr == '') ? ((c == '') ? '' : c) : (addr + ((c == '') ? '' : (c + ', ')));
	addr = (addr == '') ? ((s == '') ? '' : s) : (addr + ((s == '') ? '' : (s + ' ')));
	addr = (addr == '') ? ((z == '') ? '' : z) : (addr + ((z == '') ? '' : (z)));
	return addr;
}


// Set text value
function addImg(id, value)
{
	document.getElementById(id).innerHTML = (document.getElementById(id).innerHTML == '') ? value : (document.getElementById(id).innerHTML + "<br />" + value);
}

function addImgNew(id, value)
{
	document.getElementById(id).innerHTML =  value;
}
// Remove and add big image
function addBigImgNew(id, value)
{ 
	if(value == "http://photos.flexmls.com/sbr/NoPhoto.gif") {		
		value = "http://www.homeexploring.com/P_pictures/NoPhoto.gif";
	}else if(value == "http://photos.flexmls.com/sbr/NoPhoto.jpg"){
		value = "http://www.homeexploring.com/P_pictures/NoPhoto.jpg";
	}
	document.getElementById(id).innerHTML =  (value == '') ? value : '<img src="'+value+'" alt="Image">'; 
}


// Set text value
function setText(id, value)
{
	document.getElementById(id).innerHTML = value;
}
//set boolean value converted to Y/N
function setBool(id, value)
{
	document.getElementById(id).innerHTML = (value=='1') ? 'Y' : 'N';
}


// ******************* CMA **************************


// CMA functions
function ProcessProperty(i, checkbox)
{ 
	var oPr = App.jsonData.map.markers[i].Property; 
	var selected = checkbox.checked;
	// Make AJAX call to save/delete record to a session
	/* 2007 Update: drop city, state, zip from address (common to all).  
	*var addr = App.jsonData.map.markers[i].address + " " + App.jsonData.map.markers[i].city + ", " + App.jsonData.map.markers[i].state + " " + App.jsonData.map.markers[i].zip;
	*/
	var addr = App.jsonData.map.markers[i].address;

	var Property_ProtoAJAX = null;
	var params = Serialize({Selected: selected, Status: oPr.Status, ID:oPr.ID, Addr:addr, Bed: oPr.Bedrooms, Bath:oPr.Bathrooms, SF:oPr.SF, LP:oPr.FormatedPrice, SP:oPr.SoldPrice});
	Property_ProtoAJAX = new Ajax.Request('./secure/service/prop.php',{method:'post',parameters:params,onComplete:null, onLoading:null});

	if (selected)
	{
		if (oPr.Status == 'Sold')
		{
			// Do we have max listings?
			if (CmaSoldTbl.Rows.length < 10)
			{
				CmaSoldTbl.AddRecord({ID:oPr.ID, Addr:addr, Bed: oPr.Bedrooms, Bath:oPr.Bathrooms, SF:oPr.SF, LP:oPr.FormatedPrice, SP:oPr.SoldPrice, NUM:i}, true);
			}
			else
			{
				checkbox.checked = false;
				alert("Max. of 10 sold listings gjghj gh hgj allowed.");
			}
		}
		else
		{
			// Do we have max listings?
			if (CmaActiveTbl.Rows.length < 10)
			{
				CmaActiveTbl.AddRecord({ID:oPr.ID, Addr:addr, Bed: oPr.Bedrooms, Bath:oPr.Bathrooms, SF:oPr.SF, LP:oPr.FormatedPrice, SP:oPr.SoldPrice}, true);
			}
			else
			{
				checkbox.checked = false;
				alert("Max. of 10 active listings allowed.");
			}
		}
	}	
	else
	{
		// Find row by ID
		if (oPr.Status == 'Sold')
		{
			var tbl = CmaSoldTbl;
		}
		else
		{
			var tbl = CmaActiveTbl;
		}
		for(var i=0; i<tbl.Rows.length; i++)
			if(tbl.Rows[i].ID == oPr.ID)
				tbl.Rows[i].Delete();
	}	

	//UI
	//CheckSoldProperty();
	CheckSoldProperty1();
}
function CheckSoldProperty()
{
	// UI tweaks
	if (CmaSoldTbl.Rows.length > 0 )
	{
		$('SelectProperties').style.display = "none";
		$('CalculateHomeValue').style.display = "block";
	}
	else
	{
		$('CalculateHomeValue').style.display = "none";
		$('SelectProperties').style.display = "block";
	}

}

function CheckSoldProperty1()
{
	// UI tweaks
		
	if (CmaActiveTbl.Rows.length > 0 || CmaSoldTbl.Rows.length > 0 )
	{
		//$('SelectProperties').style.display = "none";
		$('SelectProperties').style.textDecoration = "none";
		$('CalculateHomeValue').style.textDecoration = "blink";
		$('CalculateHomeValue').style.display = "block";
	}
	else
	{
		$('SelectProperties').style.textDecoration = "blink";
		$('CalculateHomeValue').style.textDecoration = "none";
		$('CalculateHomeValue').style.display = "none";
		//$('SelectProperties').style.display = "block";
	}

}

//Serialization
function _Serialize(o,name, arrayname)
{
	var s = '';
	switch(typeof(o))
	{
		case 'string':
		case 'number':
			if(arrayname)
			{
				s += encodeURIComponent(arrayname + '[' + name + "]") + "=" + encodeURIComponent(o) + "&";
			}
			else
			{
				s += encodeURIComponent(name) + "=" + encodeURIComponent(o) + "&";
			}
			break;
		case 'boolean':
			if(arrayname)
			{
				s += encodeURIComponent(arrayname + '[' + name + "]") + "=" + (o ? 1 : 0) + "&";
			}
			else
			{
				s += encodeURIComponent(name) + "=" + (o ? 1 : 0) + "&";
			}
			break;
		case 'array':
			for(i = 0; i < o.length; i++)
			{
				s += _Serialize(o[i], i, arrayname ? arrayname + '[' + name + ']' : name);
			}
			break;
		case 'object':
			for(i in o)
			{
				s += _Serialize(o[i], i, arrayname ? arrayname + '[' + name + ']' : name);
			}
			break;
		case 'function':
			//Do nothing
			break;
		default:
			throw ("Attemt to serialize an unknown type of " + typeof(o) + ", name='" + name + "', value='" + o + "'");
	}
	return s;
}

//Call this with an array or object (can be nested, probabally DOES NOT HANDLE CYCLIC REFERENCES)
function Serialize(o)
{
	var s = _Serialize(o, null, null);
	return s.substr(0, s.length - 1);
}	


// Build images
function buildImage(i, url)
{
	var currentimg = [];
	var current = [];
	var img = []; 

	currentimg[i] = new Image();

	currentimg[i].src = url;
	currentimg[i].title = 'Property Image';
	currentimg[i].id = 'dImg' + i;
	currentimg[i].width = 80;
	currentimg[i].height = 66;
	currentimg[i].className = 'smallImage';
	//currentimg[i].onclick= 'addBigImgNew("dImg","'+url+'")';
	Event.observe(currentimg[i], 'click', buildImageBig.bind(currentimg[i])); 
	//currentimg[i].onload = CustomLoad.bind(currentimg[i]);

	current[i] = currentimg[i];

	//Timeout for IE fix
	img[i] =  document.getElementById('dImg' + i);

	/* Might be required by SAFARI
	var imgNode = document.createElement("IMG");
	imgNode.setAttribute("src",current[i].src);
	imgNode.setAttribute("title",current[i].title);
	imgNode.className = 'smallImage';
	imgNode.setAttribute("id",current[i].id);
	*/
	img[i].parentNode.replaceChild(current[i], img[i]);
}
function buildImageBig()
{
	addBigImgNew("dImg", this.src);	
}

