﻿// extensions for String

String.prototype.CrLf = function() {
	return this+"\r\n";
}

String.prototype.Br = function() {
	return this+"<br>";
}

String.prototype.Php = function(val) {
	return this+"<?php echo $"+val+"; ?>";
}

String.prototype.GetID = function() {
	return document.getElementById(this);
}

// deprecated
String.prototype.crlf = function() {
	return this+"\r\n";
}

String.prototype.getid = function() {
	return document.getElementById(this);
}

var _attrs_ = "";
var _sel_ = "";

String.prototype.ColSpan = function(val) {
	_attrs_ += " colspan='"+val+"'";
	return this;
}

String.prototype.RowSpan = function(val) {
	_attrs_ += " rowspan='"+val+"'";
	return this;
}

// deprecated
String.prototype.colspan = function(val) {
	_attrs_ += " colspan='"+val+"'";
	return this;
}

String.prototype.rowspan = function(val) {
	_attrs_ += " rowspan='"+val+"'";
	return this;
}

String.prototype.Class = function(val) {
	_attrs_ += " class='"+val+"'";
	return this;
}

// deprecated
String.prototype.cls = function(val) {
	_attrs_ += " class='"+val+"'";
	return this;
}

String.prototype.Href = function(val) {
	_attrs_ += " href='"+val+"'";
	return this;
}

// deprecated
String.prototype.href = function(val) {
	_attrs_ += " href='"+val+"'";
	return this;
}

String.prototype.Src = function(val) {
	_attrs_ += " src='"+val+"'";
	return this;
}

String.prototype.Alt = function(val) {
	_attrs_ += " alt='"+val+"'";
	return this;
}

String.prototype.Title = function(val) {
	_attrs_ += " title='"+val+"'";
	return this;
}

String.prototype.Width = function(val) {
	_attrs_ += " width='"+val+"'";
	return this;
}

String.prototype.Height = function(val) {
	_attrs_ += " height='"+val+"'";
	return this;
}

String.prototype.ID = function(val) {
	_attrs_ += " id='"+val+"'";
	return this;
}

// deprecated
String.prototype.src = function(val) {
	_attrs_ += " src='"+val+"'";
	return this;
}

String.prototype.alt = function(val) {
	_attrs_ += " alt='"+val+"'";
	return this;
}

String.prototype.title = function(val) {
	_attrs_ += " title='"+val+"'";
	return this;
}

String.prototype.width = function(val) {
	_attrs_ += " width='"+val+"'";
	return this;
}

String.prototype.height = function(val) {
	_attrs_ += " height='"+val+"'";
	return this;
}

String.prototype.id = function(val) {
	_attrs_ += " id='"+val+"'";
	return this;
}

String.prototype.Name = function(val) {
	_attrs_ += " name='"+val+"'";
	return this;
}

String.prototype.Type = function(val) {
	_attrs_ += " type='"+val+"'";
	return this;
}

String.prototype.Click = function(val) {
	_attrs_ += " OnClick='"+val+"'";
	return this;
}

String.prototype.Value = function(val) {
	_attrs_ += " value='"+val+"'";
	if (_sel_ != "" && val == _sel_) {
		_attrs_ += " selected='"+val+"'";
		_sel_ = "";
	}
	return this;
}

String.prototype.Selected = function(val) {
	_sel_ = val;
	return this;
}

String.prototype.Attr = function(name, val) {
	_attrs_ += " "+name+"='"+val+"'";
	return this;
}

// deprecated
String.prototype.attr = function(name, val) {
	_attrs_ += " "+name+"='"+val+"'";
	return this;
}

// tags

String.prototype.Th = function() {
	s = "<th"+_attrs_+">"+this+"</th>";
	_attrs_ = "";
	return s;
};

String.prototype.Td = function() {
	s = "<td"+_attrs_+">"+this+"</td>";
	_attrs_ = "";
	return s;
};

String.prototype.Tr = function() {
	s = "<tr"+_attrs_+">"+this+"</tr>";
	_attrs_ = "";
	return s;
};

String.prototype.Thead = function() {
	s = "<thead"+_attrs_+">"+this+"</thead>";
	_attrs_ = "";
	return s;
};

String.prototype.Tbody = function() {
	s = "<tbody"+_attrs_+">"+this+"</tbody>";
	_attrs_ = "";
	return s;
};

String.prototype.Table = function() {
	s = "<table"+_attrs_+">"+this+"</table>";
	_attrs_ = "";
	return s;
};

// deprecated
String.prototype.th = function() {
	s = "<th"+_attrs_+">"+this+"</th>";
	_attrs_ = "";
	return s;
};

String.prototype.td = function() {
	s = "<td"+_attrs_+">"+this+"</td>";
	_attrs_ = "";
	return s;
};

String.prototype.tr = function() {
	s = "<tr"+_attrs_+">"+this+"</tr>";
	_attrs_ = "";
	return s;
};

String.prototype.thead = function() {
	s = "<thead"+_attrs_+">"+this+"</thead>";
	_attrs_ = "";
	return s;
};

String.prototype.tbody = function() {
	s = "<tbody"+_attrs_+">"+this+"</tbody>";
	_attrs_ = "";
	return s;
};

String.prototype.table = function() {
	s = "<table"+_attrs_+">"+this+"</table>";
	_attrs_ = "";
	return s;
};

String.prototype.Ul = function() {
	s = "<ul"+_attrs_+">"+this+"</ul>";
	_attrs_ = "";
	return s;
};

String.prototype.Li = function() {
	s = "<li"+_attrs_+">"+this+"</li>";
	_attrs_ = "";
	return s;
};

String.prototype.A = function() {
	s = "<a"+_attrs_+">"+this+"</a>";
	_attrs_ = "";
	return s;
};

String.prototype.Img = function() {
	s = "<img"+_attrs_+">"+this+"</img>";
	_attrs_ = "";
	return s;
};

// deprecated
String.prototype.ul = function() {
	s = "<ul"+_attrs_+">"+this+"</ul>";
	_attrs_ = "";
	return s;
};

String.prototype.li = function() {
	s = "<li"+_attrs_+">"+this+"</li>";
	_attrs_ = "";
	return s;
};

String.prototype.a = function() {
	s = "<a"+_attrs_+">"+this+"</a>";
	_attrs_ = "";
	return s;
};

String.prototype.img = function() {
	s = "<img"+_attrs_+">"+this+"</img>";
	_attrs_ = "";
	return s;
};

String.prototype.P = function() {
	s = "<p"+_attrs_+">"+this+"</p>";
	_attrs_ = "";
	return s;
};

String.prototype.H2 = function() {
	s = "<h2"+_attrs_+">"+this+"</h2>";
	_attrs_ = "";
	return s;
};

// deprecated
String.prototype.p = function() {
	s = "<p"+_attrs_+">"+this+"</p>";
	_attrs_ = "";
	return s;
};

String.prototype.h2 = function() {
	s = "<h2"+_attrs_+">"+this+"</h2>";
	_attrs_ = "";
	return s;
};

String.prototype.Select = function() {
	s = "<select"+_attrs_+">"+this+"</select>";
	_attrs_ = "";
	_sel_ = "";
	return s;
};

String.prototype.Option = function() {
	s = "<option"+_attrs_+">"+this+"</option>";
	_attrs_ = "";
	return s;
};

String.prototype.Button = function() {
	s = "<button"+_attrs_+">"+this+"</button>";
	_attrs_ = "";
	return s;
};

String.prototype.Input = function() {
	s = "<input"+_attrs_+">"+this+"</input>";
	_attrs_ = "";
	return s;
};

String.prototype.tag = function(stag) {
	s = "<"+stag+_attrs_+">"+this+"</"+stag+">";
	_attrs_ = "";
	return s;
}

String.prototype.Div = function() {
	s = "<div"+_attrs_+">"+this+"</div>";
	_attrs_ = "";
	return s;
};

// extend Number object with methods for converting degrees/radians

Number.prototype.toRad = function() {  // convert degrees to radians
  return this * Math.PI / 180;
}

Number.prototype.toDeg = function() {  // convert radians to degrees (signed)
  return this * 180 / Math.PI;
}



// additional rules for jQuery validate

$.validator.addMethod("ZIP", function(value, element){
	return /^\d{5}|\d{5}-\d{4}$/.test(value);
}, "Please Enter a Valid US Zip Code");

/**
 * matches US phone number format 
 * 
 * where the area code may not start with 1 and the prefix may not start with 1 
 * allows '-' or ' ' as a separator and allows parens around area code 
 * some people may want to put a '1' in front of their number 
 * 
 * 1(212)-999-2345
 * or
 * 212 999 2344
 * or
 * 212-999-0983
 * 
 * but not
 * 111-123-5434
 * and not
 * 212 123 4567
 */
jQuery.validator.addMethod("phone", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, ""); 
	return this.optional(element) || phone_number.length > 9 &&
		phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");

// import JSON support

//var MyExtension = {
//  JSON: null
//};
//Components.utils.import("chrome://myextension/modules/JSON.js", MyExtension);

function LatLng(lat,lng) {
	this.lat = lat;
	this.lng = lng;

	this.toString = function() {
	  return '{' + this.lat + ', ' + this.lng + '}';
	}

	this.latD = function() {
		return this.lat;
	}

	this.latR = function() {
		return this.lat * Math.PI/180;
	}

	this.lngD = function() {
		return this.lng;
	}

	this.lngR = function() {
		return this.lng * Math.PI/180;
	}

	this.diff = function(rhs) {
		return new LatLng(this.lat-rhs.lat,this.lng-rhs.lng);
	}

	this.distM = function(rhs) {
		//alert("in distM");
		var d = this.diff(rhs);

		var a = Math.sin(d.latR()/2) * Math.sin(d.latR()/2) +
			Math.cos(this.latR()) * Math.cos(rhs.latR()) * 
			Math.sin(d.lngR()/2) * Math.sin(d.lngR()/2);
		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
		return 3958.747948 * c;	// dist in miles
	}

	LatLng.prototype.distVincenty = function(rhs) {
		var d = this.diff(rhs);

		var a = 6378137, b = 6356752.3142,  f = 1/298.257223563;  // WGS-84 ellipsiod
		var L = d.lngR();
		var U1 = Math.atan((1-f) * Math.tan(this.latR()));
		var U2 = Math.atan((1-f) * Math.tan(rhs.latR()));
		var sinU1 = Math.sin(U1); cosU1 = Math.cos(U1);
		var sinU2 = Math.sin(U2); cosU2 = Math.cos(U2);

		var lambda = L, lambdaP, iterLimit = 100;
		do {
			var sinLambda = Math.sin(lambda), cosLambda = Math.cos(lambda);
			var sinSigma = Math.sqrt((cosU2*sinLambda) * (cosU2*sinLambda) + 
				(cosU1*sinU2-sinU1*cosU2*cosLambda) * (cosU1*sinU2-sinU1*cosU2*cosLambda));
			if (sinSigma==0) return 0;  // co-incident points
			var cosSigma = sinU1*sinU2 + cosU1*cosU2*cosLambda;
			var sigma = Math.atan2(sinSigma, cosSigma);
			var sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;
			var cosSqAlpha = 1 - sinAlpha*sinAlpha;
			var cos2SigmaM = cosSigma - 2*sinU1*sinU2/cosSqAlpha;
			if (isNaN(cos2SigmaM)) cos2SigmaM = 0;  // equatorial line: cosSqAlpha=0 (ß6)
			var C = f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha));
			lambdaP = lambda;
			lambda = L + (1-C) * f * sinAlpha *
				(sigma + C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)));
		} while (Math.abs(lambda-lambdaP) > 1e-12 && --iterLimit>0);

		if (iterLimit==0) return 0;  // formula failed to converge

		var uSq = cosSqAlpha * (a*a - b*b) / (b*b);
		var A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)));
		var B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq)));
		var deltaSigma = B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-
			B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)));
		var s = b*A*(sigma-deltaSigma);

		return s;
	}

	LatLng.prototype.bearing = function(rhs) {
		var d = this.diff(rhs);

		var y = Math.sin(d.lngR()) * Math.cos(rhs.latR());
		var x = Math.cos(this.latR())*Math.sin(rhs.latR()) -
			Math.sin(this.latR())*Math.cos(rhs.latr())*Math.cos(d.lngR());
		var b = Math.atan2(y, x)*180/Math.PI;
		if (b < 0) b += 360;
		return (b%360);
	}
}

var resultmode = "normal";
var currenthash = "";

function showlayerhash(lbl) {
	currenthash = lbl;
	window.location.hash = lbl;
	showlayer(lbl+'Layer');
}

// this is run as soon as the main document )index.php) is loaded

function RunDocReady() {
	bump('index');
	
	hidelayers();
	hideoverlays();
	
	if (typeof(calimg) != "string") {
		// this should never happen, but just in case...
		alert("waiting...");
		setTimeout('$(document).ready($)', 50);
		return;
	}
	
	// initialization for Google maps
	
	geocoder = new GClientGeocoder();
	reasons[G_GEO_SUCCESS]            = "Success" ;
	reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value." ;
	reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address." ;
	reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons." ;
	reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given" ;
	reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded." ;
	reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed." ;

	accuracy[0] = 'Unknown' ;
	accuracy[1] = 'Country' ;
	accuracy[2] = 'Region' ;
	accuracy[3] = 'Sub-region' ;
	accuracy[4] = 'Town' ;
	accuracy[5] = 'Post code' ;
	accuracy[6] = 'Street' ;
	accuracy[7] = 'Intersection' ;
	accuracy[8] = 'Address' ;      
	accuracy[9] = 'Exact' ;      

	// history functions
	
	$.History.bind('index', function(hash) {
		hideoverlays();
		if (currenthash == hash) return; currenthash = hash;
		OpenIndexLayer(false);
	});
	
	$.History.bind('result', function(hash) {
		//alert(hash);
		if (gaCapture == "registration") {
		if (currenthash == hash) return; currenthash = hash;
		activelayer = "resultLayer";
		showactivelayer();
		} else {
		hideoverlays();
		if (currenthash == hash) return; currenthash = hash;
		//OpenResultLayer(resultmode);
		activelayer = "resultLayer";
		showactivelayer();
		}
	});
	
	$.History.bind('detail', function(hash) {
		hideoverlays();
		if (currenthash == hash) return; currenthash = hash;
		OpenDetailLayer();
	});
	
	$.History.bind('signup', function(hash) {
		hideoverlays();
		if (currenthash == hash) return; currenthash = hash;
		OpenSignupLayer();
	});
	
	$.History.bind('signupForm', function(hash) {
		hideoverlays();
		if (currenthash == hash) return; currenthash = hash;
		OpenSignupFormLayer();
	});
	
	$.History.bind('terms', function(hash) {
		hideoverlays();
		if (currenthash == hash) return; currenthash = hash;
		OpenTermsLayer();
	});
	
	$.History.bind('popup', function(hash) {
		// hopefully, this will cause popups to be skipped
		if (activeoverlay == "") window.history.go(-1);
		//alert("savehash = "+savehash+", activeoverlay = "+activeoverlay);
		//window.location.history.go(-1);
		//$.History.go(savehash);
	});

	// initialization for loginLayer

	$('a#openLogin').click(function() {
		showoverlay('loginLayer');
		$('#loginBox').show();
		$('#loginBox').vCenter();
		$('#loginLayer').bgiframe();
		clearAreas();
		return false;
	});
	
	$('a.openLogin').click(function() {
		showoverlay('loginLayer');
		$('#loginBox').show();
		$('#contactLayer').hide();
		$('#loginLayer').bgiframe();
		clearAreas();
		return false;
	});

	$(':button#cancel_login').click(function() {
		hideoverlays();
		return false;
	});
	
	// initialization for contactLayer

	

//	$('a#openContact').click(function() {
//		showoverlay('contactLayer');
//		$('#contactBox').show();
//		$('#contactBox').vCenter();
//		$('#contactLayer').bgiframe();
//		return false;
//	});

/*	$('div#headerLinks a').hover(function() {
		$(this).addClass('hover');
		},
		function() {
		$(this).removeClass('hover');
	});
*/
	$('li#menu_Link_Contact').hover(function() {
		$('#contact_Dropdown').show();
	  },
	  function() {
		$('#contact_Dropdown').hide();
	});

	$('li#menu_Link_Apartments').hover(function() {
		$('#apartments_Dropdown').show();
	  },
	  function() {
		$('#apartments_Dropdown').hide();
	});
									

	$('#closeContact').click(function() {
		hideoverlays();
		return false;
	});
	
	// initialization for ownerLayer

	

	$('a#openOwner').click(function() {
		OpenOwnerSignupOverlay();
		//showoverlay('ownerLayer');
		//$('#ownerBox').show();
		//$('#ownerBox').vCenter();
		$('#ownerLayer').bgiframe();
		return false;
	});

	$('#cancelOwner').click(function() {
		CloseOwnerSignupOverlay();
		//hideoverlays();
		return false;
	});
	
	// initialization for areasLayer

	
	// initialization for captureLayer
  
	$('a.openCapture').click(function() {
		showoverlay('captureLayer');
		$('#captureBox').show();
		$('#captureBox').vCenter();
		return false;
	});
	
	$("#capture").validate({
						   
		wrapper: "p",
						   
		focusCleanup: true,
		
		rules: {
			fname: "required",
			lname: "required",
			phone: {
				required: true,
				rangelength: [10, 12]
				},
			uname_prospect: {
				required: true,
				email: true
				},
			upass_prospect: "required"
		},
		
		messages: {
			fname: "Please specify your first name",
			lname: "Please specify your last name",
			phone: "Please enter your phone number; xxx-xxx-xxxx",
			uname_prospect: {
			required: "Please enter your e-mail address",
			email: "You must use a valid e-mail address"
			},
			upass_prospect: "Please select a password"
		}
		
	});
		
	$(':button#cancelRegister').click(function() {
		hideoverlays();
		return false;
	});
	
	// initialization for forgotLayer
	

	$('a.openForgot').click(function() {
		hideoverlays();
		showoverlay('forgotLayer');
		$('#forgotBox').show();
		$('#forgotBox').vCenter();
		$('#forgotLayer').bgiframe();
		return false;
	});
	
	$(':button#cancelForgot').click(function() {
		hideoverlays();
		return false;
	});
	
	// initialization for signupLayer
	
	$('a.openSignup').click(function(){
		var oldscobj = scobj;
		scobj = new SearchCriteriaAsObject();
		OpenSignupLayer();
		scobj = oldscobj;
		return false;
	});
	
	$('#openLogout').click(function(){
		$("#statusLine").hide();
		$("#statusLine").load("dologout.php",null,function(resp, status, obj) {
			if (status != 'success') alert(status);
			clearAreas();
			//OpenIndexLayer(false);
			window.location = "index.php";
		});
		//return false;
	});
	

	
//	$('a#getName').click(function() {
//		$('div#signup').prepend(getSignature);
//	  });

	$(".thumbs a").click(function(){
		var largePath = $(this).attr("href");

		$("#largeImg").attr({ src: largePath });
		$("#largeImgd").attr({ src: largePath });

		return false;
	});

	if (resultsavailable) {
		$("#menu_Last_Search").append("<a href='Javascript:OpenResultLayer(false)' title='Go to your most recent search results'>Last Search Results</a>");
	}
	if ((detailsavailable) && utype != 'A') {
		$("#menu_Last_Details").append("<a href='Javascript:OpenDetailLayer(false)' title='Go to your most recent apartment details'>Last Apartment Details</a>");
	}
		
	activelayer = 'indexLayer';

	if (csname && csname != "") {
		activelayer = 'resultLayer';
	}
	
	if (anonymous) {
		openCapture();
	}

	//if (showsignup) activelayer = 'signupLayer';
	
	$('#waitLayer').hide();
	$('#placeHolder').hide();
	showactivelayer();
	
	//if (showcontactus) {
	//	showoverlay('contactLayer');
	//	$('#contactBox').show();
	//	$('#contactBox').vCenter();
	//}
	
	NextTestimonial();
	
}

// searchresults is an array of arrays. the length of searchresults is the same as searchcount. each element of
// searchresults is an 11-element array in the following format:

// array("rownum", "dateentered", "area", "city", "state", "bedrooms", "rent", "apartmentID", "imgfile", "dateavailable", "streetaddress")
// note that for non-clients, the streetaddress will be 'area, city, state'.

// for now, the array can be sorted in ascending or descending order by any of these fields:
// "rownum" (the original (default) sort order)
// "rent"
// "bedrooms"
// "address"
// "dateentered"
// "dateavailable"

function GetPrefsFromObject() {
	if (scobj != null) {
		if (statepref == "") statepref = scobj.statepref;
		if (locpref == "") locpref = scobj.citypref;
		if (maxrentpref == "") maxrentpref = scobj.maxrentpref;
		if (sizepref == "") sizepref = scobj.sizepref;
		if (shorttermpref == "") shorttermpref = scobj.shorttermpref;
		if (furnishedpref == "") furnishedpref = scobj.furnishedpref;
		if (petspref == "") petspref = scobj.petspref;
		if (offstreetpref == "") offstreetpref = scobj.offstreetpref;
		if (deleadedpref == "") deleadedpref = scobj.deleadedpref;
	}
}

function populatesearch() {
	GetPrefsFromObject();
	
	if (statepref != "") {
		var stateField = "state".getid();
		for (i = 1; i < stateField.options.length; i++) {
			if (stateField.options[i].value == statepref) {
				stateField.options[i].selected = true;
				stateField.selectedIndex = i;
			}
		}
	}

	"areaSelections".getid().value=locpref;

	if (maxrentpref != 0) {
		var rentField = "maxrent".getid();
		for (i = 1; i < rentField.options.length; i++) {
			if (rentField.options[i].value == maxrentpref) {
				rentField.options[i].selected = true;
				rentField.options[0].selected = false;
				rentField.selectedIndex = i;
			} else if (rentField.options[i].selected == true) {
				rentField.options[i].selected = false;
			}
		}
	}

	// handle movedatepref one way or another

	if (sizepref != "") {
		var sizeField = "size".getid();
		for (i = 1; i < sizeField.options.length; i++) {
			if (sizeField.options[i].value == sizepref) {
				sizeField.options[i].selected = true;
				sizeField.selectedIndex = i;
			}
		}
	}

/*	if (sizepref != "") {
		var szfld = "searchForm".getid().elements["sizeField[]"];
		sizes = sizepref.split(",");
		for (i = 0; i < sizes.length; i++) {
			switch(sizes[i]) {
			case "1 Bedroom" :
				szfld[0].checked = true;
				break;
			case "1 Bedroom Apt" :
				szfld[0].checked = true;
				break;
			case "2 Bedroom" :
				szfld[1].checked = true;
				break;
			case "2 Bedroom Apt" :
				szfld[1].checked = true;
				break;
			case "3 Bedroom" :
				szfld[2].checked = true;
				break;
			case "3 Bedroom Apt" :
				szfld[2].checked = true;
				break;
			case "4 Bedroom" :
				szfld[3].checked = true;
				break;
			case "4 Bedroom Apt" :
				szfld[3].checked = true;
				break;
			case "5 Bedroom" :
				szfld[4].checked = true;
				break;
			case "5 Bedroom Apt" :
				szfld[4].checked = true;
				break;
			case "Loft" :
				szfld[5].checked = true;
				break;
			case "Room" :
				szfld[6].checked = true;
				break;
			case "Studio" :
				szfld[7].checked = true;
				break;
			}
		}
	}*/
	
	if (shorttermpref == "Yes") {
		var shorttermField = "shorttermField".getid();
		shorttermField.checked = true;
	}
	if (furnishedpref == "Yes") {
		var furnishedField = "furnishedField".getid();
		furnishedField.checked = true;
	}
	if (petspref == "Yes") {
		var petsField = "petsField".getid();
		petsField.checked = true;
	}
	if (offstreetpref == "Yes") {
		var garageField = "garageField".getid();
		garageField.checked = true;
	}
	if (deleadedpref == "Yes") {
		var deleadedField = "deleadedField".getid();
		deleadedField.checked = true;
	}
	//	if (wheelchairpref == "Yes") {
	//		var Field = document.getElementById("");
	//		theForm.wheelchairField.checked = true;
	//	}

	//createOrder();
}

function clearAreas() {
	locpref = "";
	scobj = new SearchCriteriaAsObject();
	var form = "SelectAreas".getid();
	if (!form) return;
	var area = form.area;
	for (i = 0; i < area.length; i++) {
		area[i].checked = false;
	}
	var sel = "areaSelections".getid();
	if (!sel) return;
	sel.value="";
}

function syncOldAreas(prevloc, form) {
	var area = form.area;
	var locs = prevloc.split(";");
	for (i = 0; i < area.length; i++) {
		area[i].checked = false;
		for (j = 0; j < locs.length; j++) {
			if (area[i].value == locs[j]) area[i].checked = true;
		}
	}
}

function createOrder() {
	area=document.getElementById("SelectAreas").area;
	txt="";
	for (i=0; i<area.length; i++)
	{
		if (area[i].checked)
		{
			if (txt != "") txt += ";";
			txt += area[i].value;
		}
	}
	"areaSelections".getid().value=txt;
}
		
function image_open() {
	if (pics.length > 1 || (pics.length == 1 && pics[0].length > 0)) {
		image_loc = "listings/"+pics[0]+".jpg";
	} else {
		image_loc = "image/NoPhotoAvailable2.gif";
	}
	image_loc = root+image_loc;
	imgurl = image_loc;
}

function image_prev() {
	if (seq > 1) seq -= 1; else seq = pics.length;
	if (pics.length > 1 || (pics.length == 1 && pics[0].length > 0)) {
		image_loc = "listings/"+pics[seq-1]+".jpg";
	} else {
		image_loc = "image/NoPhotoAvailable2.gif";
	}
	image_loc = root+image_loc;
	imgurl = image_loc;
}

function image_next() {
	if (seq < pics.length) seq += 1; else seq = 1;
	if (pics.length > 1 || (pics.length == 1 && pics[0].length > 0)) {
		image_loc = "listings/"+pics[seq-1]+".jpg";
	} else {
		image_loc = "image/NoPhotoAvailable2.gif";
	}
	image_loc = root+image_loc;
	imgurl = image_loc;
}

function showimage(anchor) {
	popup(imgurl, anchor, 400, 330, -400, -400);
}

function previmage_g() {
	image_prev();
	var bigimg = "largeImg".getid();
	bigimg.src = imgurl;
	var bigimga = "largeImgA".getid();
	bigimga.href = imgurl;
}

function nextimage_g() {
	image_next();
	var bigimg = "largeImg".getid();
	bigimg.src = imgurl;
	var bigimga = "largeImgA".getid();
	bigimga.href = imgurl;
}

function previmage_d() {
	image_prev();
	var bigimg = "largeImgd".getid();
	bigimg.src = imgurl;
	var bigimga = "largeImgdA".getid();
	bigimga.href = imgurl;
	var origimg = "setOrigImg".getid();
	origimg.src = imgurl;
}

function nextimage_d() {
	image_next();
	var bigimg = "largeImgd".getid();
	bigimg.src = imgurl;
	var bigimga = "largeImgdA".getid();
	bigimga.href = imgurl;
	var origimg = "setOrigImg".getid();
	origimg.src = imgurl;
}

// listingrecord is an Array with the details of the listing, except for contact and address info, and images, which are in pics
function populatedetails() {
	seq = 1;
	image_open();
	//'addressInfo'.getid().innerHTML = addressinfo;
	//'contactInfo'.getid().innerHTML = contactinfo;
	//$('#searchLinks').html(searchlinks);
	//$('#rent').html(listingrecord[0]);
	//$('#comment').html(listingrecord[1]);
	//$('#dateavailable').html(listingrecord[2]);
	//$('#bedrooms').html(listingrecord[3]);
	//$('#squarefootage').html(listingrecord[4]);
	//$('#type').html(listingrecord[5]);
	//$('#doorman').html(listingrecord[6]);
	//$('#elevator').html(listingrecord[7]);
	//$('#pets').html(listingrecord[8]);
	//$('#shortterm').html(listingrecord[9]);
	//$('#financialreqs').html(listingrecord[10]);
	//$('#aptnumber').html(listingrecord[11]);
	//$('#floor').html(listingrecord[12]);
	//$('#deleaded').html(listingrecord[13]);
	//$('#furnished').html(listingrecord[14]);
	//$('#garage').html(listingrecord[15]);
	//$('#wheelchair').html(listingrecord[16]);
	//$('#healthcare').html(listingrecord[17]);
	//$('#pool').html(listingrecord[18]);
	
	var lim = pics.length;
	if (lim > 7) lim = 7;
	if (pics.length > 1 || (pics.length == 1 && pics[0].length > 0)) {
		s = "";
		for (i = 1; i <= lim; i++) {
			var imgsrc = root+"listings/"+pics[i-1]+".jpg";
			//if (browser == "IE") {
			//if (browser == "Mozilla" && Number(browserversion) <= 4.0) {
			if (browser == "MSIE") {
				s += "".src(imgsrc).alt('Image '+i).width('32').height('24').img().href(imgsrc).title('Image '+i).a().li();
			} else {
				s += "".src(imgsrc).alt('Image '+i).img().href(imgsrc).title('Image '+i).a().li();
			}
		}
		$('#imageThumbs_Details').html(s.cls('thumbs').ul());
	} else {
		$('#imageThumbs_Details').html("");
	}

	var bigimg = "largeImgd".getid();
	bigimg.src = imgurl;
	var bigimga = "largeImgdA".getid();
	bigimga.href = imgurl;

	$(".thumbs a").click(function(){
		var largePath = $(this).attr("href");
		$("#largeImgd").attr({ src: largePath });
		$("#largeImgdA").attr({ href: largePath });
		$("#setOrigImg").attr({ src: largePath });
		return false;
	});
	
	
	if($.browser.msie6) {
				
		$('#largeImgdA').click(function(){ //when the large image in details is clicked
										
				$('#header').after('<div id="origImage"><p class="closeOrigImage"><a id="closeOrigImage">close</a></p><img id="setOrigImg" alt="Original image" src="" /><div class="print"> </div></div>'); // insert the origImage div that will contain a loop of all the available images at 400 px wide or less
			
			//$('#origImage').show(); //the image is initially hidden, so we want it to show.
			
				$('#origImage img').css({backgroundColor:"#FFFFFF", width: "0", height: "0" });
				
				$('#origImage img').css({width: "auto", height: "auto", display:"block" });
				
				$('#origImage').css({backgroundColor:"#FFFFFF", borderColor:"#666666", borderStyle:"solid", borderWidth:"1px", padding:"42px", display:"block", position:"absolute" });

				var setImgSrc = $(this).attr("href");
				$('#setOrigImg').attr({ src: setImgSrc });
				
				$('#origImage').vCenter();
		
				$('#origImage').css({backgroundColor:"#FFFFFF", borderColor:"#666666", borderStyle:"solid", borderWidth:"1px", padding:"42px" });
				
				$('#origImage img').css({backgroundColor:"#FFFFFF"});
		
				var wpr_width = $('#wrapper').width();
				
				var img_width = $('#origImage img').width();
				
				//$('div#listingDetails').text(img_width);
			
				var imgDiv_width = $('#origImage').width();
				
				var imgRemainder = img_width-400;
			
				if (img_width < 400) {
						$('#origImage img').width(img_width);
					}
					else {
						$('#origImage img').width(400);
					}
					
				if (img_width > 400) {
				
					img_marg = (wpr_width-imgDiv_width+imgRemainder);
					
					}
					
				else {
				
					img_marg = (wpr_width-imgDiv_width);
					
					}	
				
			$('#origImage').css({marginLeft:(img_marg/2-42)});
						
			var scrollTopLoop = $('#origImage').scrollTop();
		
		
//				var img_width = $('#origImage img').width(); //get the image width
//				
//				var img_height = $('#origImage img').height(); //get the image height
				
				// try this instead:
				//var imgtemp = new Image();
				//imgtemp.src = imgurl;
				//img_width = imgtemp.width;
				//img_height = imgtemp.height;
				//alert("width = "+img_width+", height = "+img_height);
					
				//$('div.print').append('<p>height: ' + img_height + '</p>'); //confirm dimension
			
				//$('div.print').append('<p>height: ' + img_height + '</p>');

			
			var windowHeight = $(window).height(); //get the window height
			
					if ( pics.length > 1 ) {
							
					 $('p.closeOrigImage').after('<p class="next"><a class="next">next</a><span class="prev">&nbsp;|&nbsp;<a class="prev">prev</a></span></p>');
							 
					 }
					 
				$('span.prev').hide();
							
				$('a.next').click(function() {
					$('#setOrigImg').attr({ src: nextimage_d() });
					$('span.prev').show();
					return false;
				});
										
				$('a.prev').click(function() {
					$('#setOrigImg').attr({ src: previmage_d() });
					return false;
				});
										
			$('#closeOrigImage').click(function() {
				$('#origImage').remove();
				return false;
				});
			
			return false;
		
		});
		
	
	}else {
	
	var image = "largeImgd".getid();
	
	if ( image.src != root+"image/NoPhotoAvailable2.gif" ) {
		
		$('#largeImgdA').click(function(){

		var scrollTopLarge = $('#largeImgdA').scrollTop();
		
		$('#header').after('<div id="origImage"><p class="closeOrigImage"><a id="closeOrigImage">close</a></p><img id="setOrigImg" alt="Original image" src="" /><p class="div_width"> </p></div>');
		
		$('#origImage').show();
		
		var origimg = "setOrigImg".getid();
		origimg.src = imgurl;
		
		var largePathOrig = $(this).attr("href");
		$('#setOrigImg').attr({ src: largePathOrig });
		
		$('#origImage').vCenter();
		
		$('#origImage').css({backgroundColor:"#FFFFFF", borderColor:"#666666", borderStyle:"solid", borderWidth:"1px", padding:"42px" });
		
		$('#origImage img').css({backgroundColor:"#FFFFFF"});

		var wpr_width = $('#wrapper').width();
		
		var img_width = $('#origImage img').width();
		
		//$('div#listingDetails').text(img_width);
	
		var imgDiv_width = $('#origImage').width();
		
		var imgRemainder = img_width-400;
	
		if (img_width < 400) {
				$('#origImage img').width(img_width);
			}
			else {
				$('#origImage img').width(400);
			}
			
		if (img_width > 400) {
		
			img_marg = (wpr_width-imgDiv_width+imgRemainder);
			
			}
			
		else {
		
			img_marg = (wpr_width-imgDiv_width);
			
			}	
		
	
	$('#origImage').css({marginLeft:(img_marg/2-42)});
				
	var scrollTopLoop = $('#origImage').scrollTop();
	
	if ( pics.length > 1 ) {
				
		 $('p.closeOrigImage').after('<p class="next"><a class="next">next</a><span class="prev">&nbsp;|&nbsp;<a class="prev">prev</a></span></p>');
				 
		 }
		 
	$('span.prev').hide();
				
	$('a.next').click(function() {
		$('#setOrigImg').attr({ src: nextimage_d() });
		$('span.prev').show();
		return false;
	});
							
	$('a.prev').click(function() {
		$('#setOrigImg').attr({ src: previmage_d() });
		return false;
	});
			
	
	$('#closeOrigImage').click(function() {
		$('#origImage').remove();
		$('#largeImgdA').scrollTop(scrollTopLarge);
		return false;
	});
			
	//$('p.div_width').text();

	return false;
	});
		
	}
	
	else {
		
		$('#largeImgdA').removeAttr('href');
		$('div#imageThumbs_Details').remove();
	}

	$('a.openSignup').click(function(){
		OpenSignupLayer();
		//showlayer('signupLayer');
		return false;
	});
	
	}
}

//function nextTestimonial() {
//	tnum = tnum+1;
//	if (tnum >= tfiles.length) tnum = 0;
//	"resultgetTestimonial".getid().src = root+"testimonials/"+tfiles[tnum];
//	"detailgetTestimonial".getid().src = root+"testimonials/"+tfiles[tnum];
//	"indexgetTestimonial".getid().src = root+"testimonials/"+tfiles[tnum];
//  //return ($tfiles[$tnum]);
//}
 
function findObj( oName, oFrame, oDoc ) {
  if( !oDoc ) { if( oFrame ) { oDoc = oFrame.document; } else { oDoc = window.document; } }
  if( oDoc[oName] ) { return oDoc[oName]; } if( oDoc.all && oDoc.all[oName] ) { return oDoc.all[oName]; }
  if( oDoc.getElementById && oDoc.getElementById(oName) ) { return oDoc.getElementById(oName); }
  for( var x = 0; x < oDoc.forms.length; x++ ) { if( oDoc.forms[x][oName] ) { return oDoc.forms[x][oName]; } }
  for( var x = 0; x < oDoc.anchors.length; x++ ) { if( oDoc.anchors[x].name == oName ) { return oDoc.anchors[x]; } }
  for( var x = 0; document.layers && x < oDoc.layers.length; x++ ) {
    var theOb = findObj( oName, null, oDoc.layers[x].document ); if( theOb ) { return theOb; } }
  if( !oFrame && window[oName] ) { return window[oName]; } if( oFrame && oFrame[oName] ) { return oFrame[oName]; }
  for( var x = 0; oFrame && oFrame.frames && x < oFrame.frames.length; x++ ) {
    var theOb = findObj( oName, oFrame.frames[x], oFrame.frames[x].document ); if( theOb ) { return theOb; } }
  return null;
}

function escvar(nm, val) {
	return (nm+"="+escape(val));
}

function getSearchCriteriaFromJS() {
	var a = new Array();
	
	a["statepref"] = statepref;
	a["citypref"] = locpref;
	a["areapref"] = "";
	a["maxrentpref"] = maxrentpref;
	a["sizepref"] = sizepref;
	a["shorttermpref"] = shorttermpref;
	a["furnishedpref"] = furnishedpref;
	a["petspref"] = petspref;
	a["offstreetpref"] = offstreetpref;
	a["wheelchairpref"] = wheelchairpref;
	a["deleadedpref"] = deleadedpref;
	a["movedatepref"] = movedatepref;

	return a;
}

function getSearchCriteriaFromForm(theForm) {
	var a = new Array();
	
/*	var szfld = findObj("sizeField[]");
	if (!szfld) szfld = findObj("sizeField");
	sfv = "";
	for (j = 0; j < 8; j++) {
		if (szfld[j].checked) {
			if (sfv.length > 0) sfv += ",";
			sfv += szfld[j].value;
		}
	}
*/

	a["statepref"] = theForm.state.value;
	a["citypref"] = theForm.areaSelections.value;
	a["areapref"] = "";
	a["maxrentpref"] = theForm.Max_Rent.value;
	a["sizepref"] = theForm.size.value;
	a["shorttermpref"] = theForm.shorttermField.checked?theForm.shorttermField.value:"";
	a["furnishedpref"] = theForm.furnishedField.checked?theForm.furnishedField.value:"";
	a["petspref"] = theForm.petsField.checked?theForm.petsField.value:"";
	a["offstreetpref"] = theForm.offstreetField.checked?theForm.offstreetField.value:"";
	a["wheelchairpref"] = "";
	a["deleadedpref"] = theForm.deleadedField.checked?theForm.deleadedField.value:"";
	a["movedatepref"] = theForm.movedatepref.value;
	
	if (statepref != a["statepref"]) statepref = a["statepref"];
	if (locpref != a["citypref"]) locpref = a["citypref"];
	if (maxrentpref != a["maxrentpref"]) maxrentpref = a["maxrentpref"];
	if (sizepref != a["sizepref"]) sizepref = a["sizepref"];
	if (shorttermpref != a["shorttermpref"]) shorttermpref = a["shorttermpref"];
	if (furnishedpref != a["furnishedpref"]) furnishedpref = a["furnishedpref"];
	if (petspref != a["petspref"]) petspref = a["petspref"];
	if (offstreetpref != a["offstreetpref"]) offstreetpref = a["offstreetpref"];
	if (deleadedpref != a["deleadedpref"]) deleadedpref = a["deleadedpref"];
	if (movedatepref != a["movedatepref"]) movedatepref = a["movedatepref"];

	return a;
}

function getSearchCriteria() {
	var theForm = "searchForm".getid();
	
	if (theForm == null) {
		return getSearchCriteriaFromJS();
	} else {
		return getSearchCriteriaFromForm(theForm);
	}
}

function MsgObject(to, from, subject, body) {
	this.to = to;
	this.from = from;
	this.subject = subject;
	this.body = body;
}

function SearchCriteriaAsObject() {
	var sc = getSearchCriteria();

	this.statepref = sc["statepref"];
	this.citypref = sc["citypref"];
	this.areapref = sc["areapref"];
	this.maxrentpref = sc["maxrentpref"];
	this.sizepref = sc["sizepref"];
	this.shorttermpref = sc["shorttermpref"];
	this.furnishedpref = sc["furnishedpref"];
	this.petspref = sc["petspref"];
	this.offstreetpref = sc["offstreetpref"];
	this.wheelchairpref = sc["wheelchairpref"];
	this.deleadedpref = sc["deleadedpref"];
	this.movedatepref = sc["movedatepref"];
}

function saveURL(mode) {
	var sc = getSearchCriteria();
	
	url = "savecriteria.php?mode="+mode;
	url += "&"+escvar("statepref", sc["statepref"]);
	url += "&"+escvar("citypref", sc["citypref"]);
	url += "&"+escvar("areapref", sc["areapref"]);
	url += "&"+escvar("maxrentpref", sc["maxrentpref"]);
	url += "&"+escvar("sizepref", sc["sizepref"]);
	url += "&"+escvar("shorttermpref", sc["shorttermpref"]);
	url += "&"+escvar("furnishedpref", sc["furnishedpref"]);
	url += "&"+escvar("petspref", sc["petspref"]);
	url += "&"+escvar("offstreetpref", sc["offstreetpref"]);
	url += "&"+escvar("wheelchairpref", sc["wheelchairpref"]);
	url += "&"+escvar("deleadedpref", sc["deleadedpref"]);
	url += "&"+escvar("movedatepref", sc["movedatepref"]);
	
	return url;
}

function signupURL() {
	var sc = getSearchCriteria();
	
	url = "signup.php?";
	url += escvar("statepref", sc["statepref"]);
	url += "&"+escvar("citypref", sc["citypref"]);
	url += "&"+escvar("areapref", sc["areapref"]);
	url += "&"+escvar("maxrent", sc["maxrentpref"]);
	url += "&"+escvar("size", sc["sizepref"]);
	url += "&"+escvar("shortterm", sc["shorttermpref"]);
	url += "&"+escvar("furnished", sc["furnishedpref"]);
	url += "&"+escvar("pets", sc["petspref"]);
	url += "&"+escvar("offstreet", sc["offstreetpref"]);
	url += "&"+escvar("wheelchair", sc["wheelchairpref"]);
	url += "&"+escvar("deleaded", sc["deleadedpref"]);
	url += "&"+escvar("movedate", sc["movedatepref"]);
	return url;
}

function populateSignupForm() {
	if (level == "Bronze") {
		$('div#signup h1').html('Register your $29 Bronze Membership');
		$('p.guarantee').html('At Rental Beast we are here for you to ensure you find an apartment. Please contact Rental Beast Customer Service promptly in the event you experience any difficulties with our service. Rental Beast guarantees to find you an apartment in your specified criteria during the term of your search (from the day you sign up with Rental Beast to the day you specified as your moving date when you signed up). If Rental Beast fails to locate you an apartment during this time period, you have the right to request a refund of your service charge up to sixty days beyond your specified moving date. To receive your refund please sends us a letter, Fax or Email, briefly detailing your apartment search. Please enclose a copy of your lease agreement. Please allow five to ten business days to process your refund. The apartment that you move in to must not be listed in our database for you to receive a refund. By submitting this form you agree that you are moving. Your decision not to move is not a condition for a refund; however, in compensation, your account will be reactivated the next time you move.');
	} else if (level == "Silver") {
		$('div#signup h1').html('Register your $59 Silver Membership');
		$('p.guarantee').html('At Rental Beast we are here for you to ensure you find an apartment. Please contact Rental Beast Customer Service promptly in the event you experience any difficulties with our service. Rental Beast guarantees to find you an apartment in your specified criteria during the term of your search (from the day you sign up with Rental Beast to the day you specified as your moving date when you signed up). If Rental Beast fails to locate you an apartment during this time period, you have the right to request a refund of your service charge up to sixty days beyond your specified moving date. To receive your refund please sends us a letter, Fax or Email, briefly detailing your apartment search. Please enclose a copy of your lease agreement. Please allow five to ten business days to process your refund. The apartment that you move in to must not be listed in our database for you to receive a refund. By submitting this form you agree that you are moving. Your decision not to move is not a condition for a refund; however, in compensation, your account will be reactivated the next time you move.');
	} else {
		$('div#signup h1').html('Register your $250 Gold Membership');
		$('p.guarantee').html('At Rental Beast we are here for you to ensure you find an apartment. Please contact Rental Beast Customer Service promptly in the event you experience any difficulties with our service. Rental Beast guarantees to find you an apartment in your specified criteria during the term of your search (from the day you sign up with Rental Beast to the day you specified as your moving date when you signed up). If Rental Beast fails to locate you an apartment during this time period, you have the right to request a refund of your service charge up to sixty days beyond your specified moving date. To receive your refund please sends us a letter, Fax or Email, briefly detailing your apartment search. Please enclose a copy of your lease agreement. Please allow five to ten business days to process your refund. The apartment that you move in to must not be listed in our database for you to receive a refund. By submitting this form you agree that you are moving. Your decision not to move is not a condition for a refund; however, in compensation, your account will be reactivated the next time you move.');
	}

	if (signuparray.length != 5) return;
	var theForm = 'signupFrm'.getid();
	// signuparray contains the following, if not empty
	// [0] = fname
	// [1] = lname
	// [2] = phone
	// [3] = email (uname)
	// [4] = password
	theForm.fname.value = signuparray[0];
	theForm.lname.value = signuparray[1];
	theForm.phone.value = signuparray[2];
	theForm.email.value = signuparray[3];
	theForm.pw.value = signuparray[4];
}

function validateSignupForm() {
	var theForm = 'signupFrm'.getid();
	//var errs = new Array();
	//var errs2 = new Array();
	//if (theForm.fname.value == "") { errs[errs.length] = "first name"; }
	//if (theForm.lname.value == "") { errs[errs.length] = "last name"; }
	//if (theForm.address1.value == "") { errs[errs.length] = "street address"; }
	//if (theForm.city.value == "") { errs[errs.length] = "city"; }
	//if (theForm.stateorprovince.value == "") { errs[errs.length] = "state"; }
	//if (theForm.zip.value == "") { errs[errs.length] = "ZIP code"; }
	//if (theForm.country.value == "") { errs[errs.length] = "country"; }
	//if (theForm.phone.value == "") { errs[errs.length] = "telephone number"; }
	//if (theForm.email.value == "") { errs[errs.length] = "email address"; }
	//if (theForm.pw.value == "") { errs[errs.length] = "password"; }

	//if (theForm.pw.value != theForm.pw2.value) { errs2[errs2.length] = "password mismatch"; }
	//if (!theForm.terms.checked) { errs2[errs2.length] = "terms not agreed"; }
	
	var postargs = new SearchCriteriaAsObject();
	
	//var sc = getSearchCriteria();
	if (postargs.citypref == "") {
		var a = getSearchCriteriaFromJS();
		if (a["citypref"] != "") {
			postargs.citypref = a["citypref"];
		} else {
			//alert("please enter at least one area on the search form"); 
		}
	}

	if (level != "Silver" && level != "Bronze") level = "Gold";
	theForm.level.value = level;
	
	postargs.fname = theForm.fname.value;
	postargs.lname = theForm.lname.value;
	postargs.address1 = theForm.address1.value;
	postargs.city = theForm.city.value;
	postargs.stateorprovince = theForm.stateorprovince.value;
	postargs.canadianProvince = theForm.canadianProvince.value;
	postargs.province = theForm.province.value;
	postargs.zip = theForm.zip.value;
	postargs.country = theForm.country.value;
	postargs.phone = theForm.phone.value;
	postargs.email = theForm.email.value;
	postargs.pw = theForm.pw.value;

	postargs.company = theForm.company.value;
	postargs.address2 = theForm.address2.value;
	postargs.province = theForm.province.value;
	postargs.phone2 = theForm.phone2.value;
	postargs.email2 = theForm.email2.value;
	postargs.matches = (theForm.matches.checked)? "Yes": "No";
	postargs.rememberMe2 = (theForm.rememberMe2.checked)? "Yes": "No";
	postargs.signature = theForm.signature.value;
	postargs.level = theForm.level.value;
	
	//alert(postargs.toSource());
	
	if (checkSignup.form()) {

	//if (errs.length > 0 || errs2.length > 0) {
	//	s = "";
	//	if (errs.length > 0) {
	//		s += "The following required fields were left blank:\r\n";
	//		for (i = 0; i < errs.length; i++) {
	//			s += errs[i]+"\r\n";
	//		}
	//	}
	//	if (errs2.length > 0) {
	//		if (errs.length > 0) s += "\r\n";
	//		s += "The following errors were detected:\r\n";
	//		for (i = 0; i < errs2.length; i++) {
	//			s += errs2[i]+"\r\n";
	//		}
	//	}
	//	alert(s);
	//	theForm.action = "";
	//} else {
		//theForm.action = signupURL();
		//return true;
		StartSignup(postargs);
		//return true;
	}
	return false;
}

function openSignupForm(lvl) {
	level = lvl;
	GetPrefsFromObject();
	
	//var areas;
	//if ("searchForm".getid() == null) areas = locpref;
	//else areas = "searchForm".getid().areaSelections.value;
	//if (areas != "") {
		OpenSignupFormLayer();
		//showlayer('signupFormLayer');
	//} else {
	//	OpenIndexLayer(true);
	//	alert('Please select your apartment preferences. Then click "Continue to Sign Up".');
	//	//showlayer('indexLayer');
	//}
}
	
function autoSubmit(name) {
    name.getid().submit();
}

// the layers are named indexLayer, resultLayer, detailLayer, signupLayer, signupFormLayer, termsLayer
// exactly one of these should be visible at the end of the .ready function

// wrapper and overlay are always visible

// the overlays are named areasLayer, contactLayer, loginLayer, imageLayer, captureLayer, forgotLayer
// exactly one of these should be visible when there is to be an overlay

// overlays are made visible within .click functions, and are hidden when the overlay is closed

// also, within termsLayer, exactly one of termsBronze, termsSilver and termsGold should be visible when the termsLayer is visible

var activelayer = "";
var activeoverlay = "";
var savehash = "";

function hidelayers() {
	$('#indexLayer').hide();
	$('#resultLayer').hide();
	$('#detailLayer').hide();
	$('#signupLayer').hide();
	$('#signupFormLayer').hide();
	$('#termsLayer').hide();
	
	activelayer = 'indexLayer';
}

function hideoverlays() {
	if (activeoverlay == "") {
		$('#areasLayer').hide();
		$('#contactLayer').hide();
		$('#loginLayer').hide();
		$('#imageLayer').hide();
		$('#captureLayer').hide();
		$('#ownerLayer').hide();
		$('#forgotLayer').hide();
		$('#popupLayer').hide();
		$('#addListingLayer').hide();
		$('p.remove').remove();
	} else {
		$('#'+activeoverlay).fadeOut(300);
		$('a #kampylink').show();
		// this can't be done, because it reloads the page
		//window.location.hash = savehash;
		//$.History.go(savehash);
		activeoverlay = "";
	}
}

function showactivelayer() {
	if (activelayer == 'indexLayer') {
		OpenIndexLayer(false);
		$('#footer').show('slow');
		//get listing count and add to div
		/*$.get("listingCount.php", 
		function(data){
			var getCount = data;
			$('span#listingCount').html("Current Active Listings <span style='color:#FF5E07;'>" + getCount + "</span>");	
		});*/
	} else if (activelayer == 'resultLayer') {
		if (csname && (csname != "")) OpenCannedSearch(csname);
		else OpenResultLayer("normal");
	} else if (activelayer == 'detailLayer') {
		OpenDetailLayer();
//	} else if (goSignup == "signup") {
//		activelayer == 'signupFormLayer'
//		OpenSignupFormLayer();
	} else {
		$('#'+activelayer).show();
	}
}

function showlayer(name) {
	//if (name != 'indexLayer' && activelayer == name) {
	//	return;
	//}
	hidelayers();
	NextTestimonial();
	activelayer = name;
	bump(name);
	//window.location.hash = name;
	window.scrollTo(0,0);
	$('#'+name).show();
//	window.location.hash = name;
	//window.location.hash = name.substring(0,name.length-5);
}

function showoverlay(name) {
	hideoverlays();
	$('#'+name).show('slow');
	activeoverlay = name;
	$('<p class="remove"><a class="closeOverlay" onclick="javascript: hideoverlays();">close</a></p>').prependTo('#'+name);
}

function openCapture() {
	showoverlay('captureLayer');
	$('#captureBox').show();
	$('#captureBox').vCenter();
	$('#captureLayer').bgiframe();
}

hidelayers();
hideoverlays();

var checkSearch;

function OpenIndexLayer(signup) {
	$("#activelayer").load("loadindexlayer.php",null,function(resp, status, obj) {
		if (status != 'success') alert(status);
		populatesearch();
		
		dpoptions = new Object();
		dpoptions.showOn = 'both';
		dpoptions.buttonImage = calimg;
		dpoptions.buttonImageOnly = true;
		//dpoptions.dateFormat = 'yy-mm-dd';
		dpoptions.dateFormat = 'dd M yy';
		dpoptions.minDate = '0d';
		dpoptions.maxDate = '6y';
		dpoptions.hideIfNoPrevNext = true;
		dpoptions.firstDay = 0;
		dpoptions.changeFirstDay = false;

		$('#movedatepref').datepicker(dpoptions);
		//$('#movedatepref').datepicker({showOn: 'both', buttonImage: calimg, buttonImageOnly: true, dateFormat: 'yy-mm-dd', minDate: '0d', maxDate: '6y', hideIfNoPrevNext: true, firstDay: 0, changeFirstDay: false});

		$('a#openAreas').click(function() {
			OpenAreasOverlay();
			return false;
		});
		
			$('#areaSelections').focus(function() {
			OpenAreasOverlay();
			return false;
		});		
		
		if (signup) {
			$('h1#findApartment').replaceWith('<h1 id="selectPreferences" class="CTR">Your Apartment Preferences</h1>');
			$('a.backSignup').show();
			$(':submit#searchApartment').hide();
		} else {
			$('h1#findApartment').replaceWith('<h1 id="selectPreferences" class="CTR">Find Your New Apartment</h1>');
			$('a.backSignup').hide();
			$(':submit#searchApartment').show();
			$('#searchApartment').click(function () {
				if (checkSearch.form()) {
					CreateResultLayer('normal');
				} else {
					alert("Please correct the errors in the search form before proceeding");
				}
				return false;
			});
		}
		
		$.get('apartments.html', function(data) {
		  $('#bostonApartments').html(data);
		  //alert('Load was performed.');
		});

	
		checkSearch = $('#searchForm').validate({
			focusCleanup: true,
			rules: {
				state: { required: true },
				Max_Rent: { required: true },
				areaSelections: { required: true }
			},
			messages: {
				state: "Please select a state",
				areaSelections: "Please enter at least one area"
			}
		});
		
		$('a.openSignup').click(function(){
		OpenSignupLayer();
		//showlayer('signupLayer');
		return false;
		});
		
		$('a.backSignup').click(function(){
			if (checkSearch.form()) {
				var oldscobj = scobj;
				scobj = new SearchCriteriaAsObject();
				OpenSignupFormLayer();
				scobj = oldscobj;
			} else {
				alert("Please correct the errors in the search form before proceeding");
			}
			return false;
		});
		
		/*if (utype != 'A' && browser != "MSIE") {
			$('#col2Search').css({'backgroundColor':'rgba(300 ,300, 300, 0.75)', 'padding':'1em' });
			$('#col3Search').css({'marginLeft':'1em', 'width':'18em' });
			.css({backgroundColor:"#FFFFFF", width: "0", height: "0" })
		} else if (utype != 'A') {
			$('#col2Search').css({'backgroundColor':'#FFFFFF', 'padding':'1em' });
			$('#col3Search').css({'marginLeft':'1em', 'width':'18em' });
			.css({backgroundColor:"#FFFFFF", width: "0", height: "0" })
		}*/
		
		showlayerhash('index');
		//window.location.hash = 'index';
		//showlayer('indexLayer');
		
	});
}

function CloseIndexLayer() {
	$("#activelayer").html("");
}

function submitSearch() {
	_gaq.push('Search', 'Find Your Apartment', 'indexLayer');
	_gaq.push('/Registration/searchButton');
}

function OpenOwnerSignupOverlay() {
	showoverlay('ownerLayer');
	$('#ownerBox').show();
	$('#ownerBox').vCenter();
	$('#contactLayer').hide();
}

function CloseOwnerSignupOverlay() {
	hideoverlays();
}

function OpenAreasOverlay() {
	$("#areasLayer").load("loadareas.php",null,function(resp, status, obj) {
		if (status != 'success') alert(status);
		
		var prevloc = "areaSelections".getid().value;

		if (prevloc != "") {
			syncOldAreas(prevloc, this.lastChild);
		}
		
		showoverlay('areasLayer');
		
		//Add the intrusctions and button for areasLayer
		$('<div style="margin:1em; background-color:#FFFFFF;padding:1em"><h3>Check or uncheck as many cities or neighborhoods as you like. <br />Questions about Boston? We can help. <br /><em>Call us: 888-244-6696</em></h3><input type="button" name="addAreas" id="addAreas" value="I'+"'"+'m done adding areas"></div>').prependTo('#areasLayer');
		
		//
				
		$('a #kampylink').hide();

		// hide all villages
		//$("ul.CityMultiple").hide();

		$("li.cityVillage").mousedown(function () {
			//$(this).nextAll().show();
			$(this).next().children().children().attr('checked', false);
			return false;
		});
		
		$('li.villageList').mousedown(function () {
			//$(this).children().attr('checked', true);
			$(this).parent().prev().children().removeAttr('checked');
			return false;
		});
		
		$('#cancelArea').click(function() {
			hideoverlays();
			return false;
		});
		
		$('#areasLayer').bgiframe();
						
		$('#cancelAreasbutton').click(function() {
			hideoverlays();
			return false;
		});

		$('#addAreas').click(function() {
			CloseAreasOverlay();
			//return false;
		});
		
	});

}

function CloseAreasOverlay() {
	activeoverlay = "";
	hideoverlays();
	createOrder();
	$("#areasLayer").html("");
}

function OpenCannedSearch(name) {
	resultmode = "normal";
	$("#activelayer").load("loadresultlayer.php",{ 'mode':'cannedsearch','name':""+name+"" },function(resp, status, obj) {
		if (status != 'success') alert(status);

		$('.thumbOver a').mouseover(function(){
			showoverlay('imageLayer');
			$('#imageGallery').show();
		});

		$('#closeGallery').click(function(){
			hideoverlays();

			return false;
		});

		$('#cancelSearch').click(function(){
			//alert("CancelSearch");
			OpenIndexLayer(false);
			//window.location.hash = "normal";
			return false;
		});
		
		//alert("canned search = "+name);
		
		//alert("canned search = "+gaCapture);
		
		if (gaCapture == "registration") {
			openCapture();
		}
		
		populateresults();
		
		if (name == 'Boston Short') {
			$('#col2Result h1').replaceWith('<h1>We found ' + searchcount + ' Short Term apartments for you</h1>');
		}
		else if (name == 'North Shore') {
			$('#col2Result h1').replaceWith('<h1>We found ' + searchcount + ' North Shore apartments for you</h1>');
		}
		else if (name == 'emailBlast') {
			$('#col2Result h1').replaceWith('<h1>Featured Apartments</h1>');
		}		
		else if (name == 'South Shore') {
			$('#col2Result h1').replaceWith('<h1>We found ' + searchcount + ' South Shore apartments for you</h1>');
		} else {
		$('#col2Result h1').replaceWith('<h1>We found ' + searchcount + ' ' +  city + ' apartments for you</h1>');
		}
				
		showlayerhash('result');
		//currenthash = 'result';
		//window.location.hash = 'result';
		//showlayer('resultLayer');
	});
}

function OpenResultLayer(mode) {
	resultmode = mode;
	$("#activelayer").load("loadresultlayer.php",{ 'mode':(mode==null?'normal':mode) },function(resp, status, obj) {
		if (status != 'success') alert(status);
		
		$('a.openSignup').click(function(){
		OpenSignupLayer();
		//showlayer('signupLayer');
		return false;
		});
		
		$('.easyGuarantee').click(function() {
			$('.easySteps').toggle();
		});	
		
		$('.levels dd').hide();
		
		$('dt.showDD').click(function() {
			$(this).nextAll().toggle();
		});

		var img = root+'image/bronze.gif';
		$('.bronze').css('background-image','url('+img+')');

		img = root+'image/silver.gif';
		$('.silver').css('background-image','url('+img+')');

/*		img = root+'image/gold.gif';
		$('.gold').css('background-image','url('+img+')');
*/

		$('.thumbOver a').mouseover(function(){
			showoverlay('imageLayer');
			$('#imageGallery').show();
		});

		$('#closeGallery').click(function(){
			hideoverlays();

			return false;
		});

		$('#cancelSearch').click(function(){
			//alert("CancelSearch");
			OpenIndexLayer(false);
			//window.location.hash = "normal";
			return false;
		});
		
		//alert("OpenResultLayer: "+mode);

		populateresults();
		showlayerhash('result');
		//currenthash = 'result';
		//window.location.hash = 'result';
		//showlayer('resultLayer');
	});
}

function CloseResultLayer() {
	$("#activelayer").html("");
}

function CreateResultLayer(mode) {
	var postargs = new SearchCriteriaAsObject();
	postargs.mode = mode;
	//scobj = new SearchCriteriaAsObject();
	//alert(postargs.toSource());
	//alert("CreateResultLayer");
	$("#statusLine").hide();
	$("#statusLine").load("createresultlayer.php",postargs,function(resp, status, obj) {
		if (status != 'success') alert(status);
		OpenResultLayer(mode);
	});
}

function CreateDetailLayer(aptID) {
	$("#statusLine").hide();
	$("#statusLine").load("createdetaillayer.php",{ 'id': aptID },function(resp, status, obj) {
		if (status != 'success') alert(status);
		if (utype != 'A') {
			$("#statusLine").show();
			OpenDetailLayer();
			hideoverlays();
		} else {
			openCapture();
		}
	});
}

function OpenDetailLayer() {
	$("#activelayer").load("loaddetaillayer.php",null,function(resp, status, obj) {
		if (status != 'success') alert(status);
		
		populatedetails();
		//alert("publictransit = "+publictransit);
		if (publictransit) $("#nearestsubway").html(publictransit);

		$('#cancelDetail').click(function(){
			OpenResultLayer("normal");
		});
		
		$('.easyGuarantee').click(function() {
			$('.easySteps').toggle();
		});	
		
		$('.levels dd').hide();
		
		$('dt.showDD').click(function() {
			$(this).nextAll().toggle();
		});

		var img = root+'image/bronze.gif';
		$('.bronze').css('background-image','url('+img+')');

		img = root+'image/silver.gif';
		$('.silver').css('background-image','url('+img+')');

		img = root+'image/gold.gif';
		$('.gold').css('background-image','url('+img+')');

		
		showlayerhash('detail');
		//window.location.hash = 'detail';
		//showlayer('detailLayer');
	});
}

function CloseDetailLayer() {
	$("#activelayer").html("");
}

function SaveCriteria() {
	var postargs = new SearchCriteriaAsObject();
	
	$("#statusLine").load("savecriteria.php",postargs,function(resp, status, obj) {
		if (status != 'success') alert(status);
		$("#statusLine").html("<p align='left'>Criteria saved</p>");
		$("#statusLine").show();
	});
}

function OpenSignupLayer() {
	GetPrefsFromObject();
	
	$("#activelayer").load("loadsignuplayer.php",null,function(resp, status, obj) {
		if (status != 'success') alert(status);
				
		$('.easyGuarantee').click(function() {
			$('.easySteps').toggle();
		});							   

		var img = root+'image/bronze.gif';
		$('.bronze').css('background-image','url('+img+')');

		img = root+'image/silver.gif';
		$('.silver').css('background-image','url('+img+')');

		img = root+'image/gold.gif';
		$('.gold').css('background-image','url('+img+')');

		showlayerhash('signup');
		//window.location.hash = 'signup';
		//showlayer('signupLayer');
	});
}

var checkSignup;

function OpenSignupFormLayer() {
	GetPrefsFromObject();
	
	$("#activelayer").load("loadsignupformlayer.php",null,function(resp, status, obj) {
		if (status != 'success') alert(status);
	
		checkSignup = $('#signupFrm').validate({
			focusCleanup: true,
			wrapper: 'p',
			rules: {
				fname: { required: true },
				lname: { required: true },
				address1: { required: true },
				city: { required: true },
				stateorprovince: { required: true },
				zip: { required: true, ZIP: true },
				country: { required: true },
				phone: { required: true, phone: true },
				email: { required: true, email: true, remote: "emailcheck.php" },
				pw: { required: true },
				pw2: { required: true, equalTo: '#pw' },
				terms: { required: true }
			},
			messages: {
				fname: "Please enter your first name",
				lname: "Please enter your last name",
				address1: "Please enter your street address",
				city: "Please enter the city where you live",
				stateorprovince: "Please enter the state",
				country: "Please enter the country",
				zip: { required: "Please enter a ZIP code", ZIP: "Please enter a valid (5 or 9-digit) ZIP code" },
				phone: { required: "Please enter a telephone number where you can be reached", phone: "Please enter a valid phone number" },
				email: { required: "Please enter an email address where you can be reached", remote: "Email address already in use, try another one" }
			}
		});

		$('a.editSpecs').click(function(){
			OpenIndexLayer(true);
			return false;
		});
		
		$('select#country').change(function() {
			var getCountry = $('select#country option:selected').val();
			if (getCountry == 'US') {
				$('p.selectState').show();
				$('p.province').hide();
				$('p.selectProvince').hide();
				$('#zip').rules('add', {
					required: true, 
					ZIP: true,
					messages: { required: "Please enter a ZIP code", ZIP: "Please enter a valid (5 or 9-digit) ZIP code" }
				});
				$('#stateorprovince').rules('add', {
					required: true,
					messages: "Please enter the state"
				   });
				$('#phone').rules('add', {
					required: true, 
					phone: true,
					messages: { required: "Please enter a telephone number where you can be reached", phone: "Please enter a valid phone number" }
				  });
			} else if (getCountry == 'CA') {
				$('p.selectProvince').show();
				$('p.selectState').hide();
				$('p.province').hide();
				$('#zip').rules('remove');
				$('#stateorprovince').rules('remove');
				$('#phone').rules('remove');
				$('#stateorprovince option:selected').val("");
			} else if (getCountry != 'US' || 'CA') {
				$('p.province').show();
				$('p.selectProvince').hide();
				$('p.selectState').hide();
				$('#zip').rules('remove');
				$('#stateorprovince').rules('remove');
				$('#phone').rules('remove');
				$('#stateorprovince option:selected').val("");
			}
	   });
		
		$('input#pw2').blur(function() {
			var getFname = $("input#fname").val();
			var getLname = $("input#lname").val();
			var getSignature = (getFname +" " + getLname);
			$('input#signature').val(getSignature);
			//$('input#signature').attr("disabled", false); 
			});
		
		populateSignupForm();
		
		showlayerhash('signupForm');
		//window.location.hash = 'signupForm';
		//showlayer('signupFormLayer');
		
		$('#openTerms').click(function() {
			OpenTermsLayer();
			return false;
		});
		
		$('input#checkTerms').click(function() {
			showlayer('signupFormLayer');
			$('#terms').attr("checked", true);
			return false;
			});
	});
}

function OpenTermsLayer() {
			if (level == 'Bronze') {
				$('#termsBronze').show();
				$('#termsSilver').hide();
				$('#termsGold').hide();
			} else if (level == 'Silver') {
				$('#termsBronze').hide();
				$('#termsSilver').show();
				$('#termsGold').hide();
			} else {
				$('#termsBronze').hide();
				$('#termsSilver').hide();
				$('#termsGold').show();
			}
			$('#termsAgree').show();
	showlayerhash('terms');
	//window.location.hash = 'terms';
	//showlayer('termsLayer');
}

function lookupZip(zip) {
	$.post("ziptocity.php", {queryString: ""+zip+""}, 
	function(data){
		var getCity = data.city;
		$('#city').val(getCity);
		var getState = data.state;
		$('#stateorprovince').attr('value', getState);
	}, "json");

}

function StartSignup(postargs) {
	$("#statusLine").hide();
	$("#statusLine").load("signup.php",postargs,function(resp, status, obj) {
		if (status != 'success') alert(status);
		autoSubmit('authorize');
	});
}

function StartForgotPassword() {
	var postargs = new Object();
	var form = "forgotPass".getid();
	//alert(form);
	postargs.forgotPassword = $('#forgotPassword').val();
	postargs.forgotName = $('#forgotName').val();
	$("#statusLine").hide();
	$("#statusLine").load("forgotpass.php",postargs,function(resp, status, obj) {
		if (status != 'success') alert(status);
		hideoverlays();
	});
}

function RemoveFromHotlist(aptid) {
	$("#statusLine").hide();
	$("#statusLine").load("addtohotlist.php",{ 'id': aptid, 'mode': 'remove' },function(resp, status, obj) {
		if (status != 'success') alert(status);
		OpenHotlist();
	});
}

function AddToHotlist(aptid) {
	if (utype != 'A') {
		$("#statusLine").hide();
		$("#statusLine").load("addtohotlist.php",{ 'id': aptid, 'mode': 'normal' },function(resp, status, obj) {
			if (status != 'success') alert(status);
			else {
				alert("We have received your showing request. Someone will contact you shortly. This apartment has been saved to your showing requests.");
			}
			//#('#addhotlistd').html("Added");
		});
	} else {
		openCapture();
	}
}

function OpenHotlist() {
	$("#statusLine").hide();
	$("#statusLine").load("createresultlayer.php",{ 'mode': 'hotlist' },function(resp, status, obj) {
		if (status != 'success') alert(status);
		OpenResultLayer('hotlist');
	});
}

function SendMail(to, from, subject, body, images) {
	$("#statusLine").hide();
	var postargs = new MsgObject(to, from, subject, body);
	if (images != null) postargs.images = images;
	
	//alert(postargs.toSource());
	
	$("#statusLine").load("htmlmail.php",postargs,function(resp, status, obj) {
		if (status != 'success') alert(status);
		//$("#statusLine").show();
	});
}

function nthtml() {
  var s1 = $("#statusLine").html();
  var countWords = s1.split(" ",12);
  var words = (countWords.join(" ")+" ...[cont]</p>");
  return (words);

/*  var offs = s1.indexOf("</p>");
  if (offs < 0) {
      if (s1.indexOf("<"+"p>") >= 0) {
          return (s1.substr(0,60)+" ...[cont]</p>");
      } else {
          return ("<"+"p>"+s1.substr(0,60)+" ...[cont]</p>");
      }
  }
  return (s1.substr(0,Math.min(60,offs))+" ...[cont]</p>");
*/}

function NextTestimonial() {
	var body;
	tnum = (tnum+3)%tfiles.length;
	fname0 = root+"testimonials/"+tfiles[(tnum)%tfiles.length];
	fname1 = root+"testimonials/"+tfiles[(tnum+1)%tfiles.length];
	fname2 = root+"testimonials/"+tfiles[(tnum+2)%tfiles.length];
	$("#statusLine").hide();
	$("#statusLine").load(fname0,null,function(resp, status, obj) {
		if (status != 'success') alert(status);
		if (browser == "MSIE") {
			body = "<a href= '"+root+"bostonApartmentsTestimonials.php' title='Read more testimonials'>"+nthtml()+"</a>";
			} else {
		body = "<a href='JavaScript:FullTestimonial(\""+fname0+"\")'>"+nthtml()+"</a>";
		}
	$("#statusLine").load(fname1,null,function(resp, status, obj) {
		if (status != 'success') alert(status);
		if (browser == "MSIE") {
			body += "<a href= '"+root+"bostonApartmentsTestimonials.php' title='Read more testimonials'>"+nthtml()+"</a>";
			} else {
		body += "<a href='JavaScript:FullTestimonial(\""+fname1+"\")'>"+nthtml()+"</a>";
		}
	$("#statusLine").load(fname2,null,function(resp, status, obj) {
		if (status != 'success') alert(status);
		if (browser == "MSIE") {
			body += "<a href= '"+root+"bostonApartmentsTestimonials.php' title='Read more testimonials'>"+nthtml()+"</a>";
			} else {
		body += "<a href='JavaScript:FullTestimonial(\""+fname2+"\")'>"+nthtml()+"</a>";
		}
				if ("resultgetTestimonial".getid()) $("#resultgetTestimonial").html(body);
				if ("detailgetTestimonial".getid()) $("#detailgetTestimonial").html(body);
				if ("indexgetTestimonial".getid()) $("#indexgetTestimonial").html(body);
			});
		});
	});
}

function FullTestimonial(fname) {
	hideoverlays();
	$("#popupText").load(fname,null,function(resp, status, obj) {
		if (status != 'success') alert(status);
		showoverlay("popupLayer");
		$('#popupLayer').bgiframe();
		$('#popupBox').show();
				
		var popupText_Height = $('#popupText').height();
		
		$('#popupBox').height(popupText_Height);
		
		var popupLayer_Height = $('#popupLayer').height();
		var popupBox_Height = $('#popupBox').height();
		var popup_marginTop = (popupLayer_Height-popupBox_Height)/2;
								
		$('#popupBox').css({marginTop:(popup_marginTop)});
					
		$('#popupText').click(function() {
			ClosePopup();	
		});
	});
}

function ClosePopup() {
	hideoverlays();
}

function OpenCaptureProspect() {
	var postargs = new Object();
	var form = "capture".getid();
	//alert(form);
	postargs.fname = form.fname_prospect.value;
	postargs.lname = form.lname_prospect.value;
	postargs.phone = form.phone_prospect.value;
	postargs.uname_prospect = form.uname_prospect.value;
	postargs.upass_prospect = form.upass_prospect.value;
	/*if (form.emaildigest.checked) {
		postargs.emaildigest = "Yes";
	} else {
		postargs.emaildigest = "No";
	}*/
	
	$("#statusLine").hide();
	$("#statusLine").load("captureprospect.php",postargs,function(resp, status, obj) {
		if (status != 'success') alert(status);
		utype = 'P';
		hideoverlays();
		$('#welcomeUser').html('<p>You are logged in. </p>');
		$('#openLogin').removeAttr('id').attr('id', 'doLogout').text('Logout');
		//$('#openLogin').unbind();
	//});
		$('#doLogout').click(function() {
			$("#statusLine").hide();
			$("#statusLine").load("dologout.php",null,function(resp, status, obj) {
				if (status != 'success') alert(status);
				clearAreas();
				//OpenIndexLayer(false);
				window.location = "index.php";
			});
		});
		var google_conversion_id = 1068353149;
		var google_conversion_language = "en_US";
		var google_conversion_format = "2";
		var google_conversion_color = "ffffff";
		var google_conversion_label = "myBECPGUkwEQ_Yy3_QM";
		$('#welcomeUser').html('<p> Welcome, '+postargs.fname+'. You are registered. </p>');
		$('#conversion').html('<script language="JavaScript" src="http://www.googleadservices.com/pagead/conversion.js"></script><noscript><img height="1" width="1" border="0" src="http://www.googleadservices.com/pagead/conversion/1068353149/?label=myBECPGUkwEQ_Yy3_QM&amp;guid=ON&amp;script=0"/></noscript>');
		/*ngt.addGoal('http://www.rentalbeast.com/WS_registeredLead');*/
	});
}

function doLogin() {
	$('#openLogin').unbind();
	var postargs = new Object();
	var form = "login".getid();
	//alert(form);
	postargs.uid = form.uid.value;
	postargs.pwd = form.pwd.value;
	utype ='';
		
	$("#statusLine").hide();
	$("#statusLine").load("logincheck.php",postargs,function(resp, status, obj) {
		if (status != 'success') alert(status);
		hideoverlays();
		$('#welcomeUser').html('<p>You are logged in. </p>');
		$('#openLogin').removeAttr('id').attr('id', 'doLogout').text('Logout');
		$('#openLogin').unbind();
	//});
		$('#doLogout').click(function() {
			$("#statusLine").hide();
			$("#statusLine").load("dologout.php",null,function(resp, status, obj) {
				if (status != 'success') alert(status);
				clearAreas();
				//OpenIndexLayer(false);
				window.location = "index.php";
			});
		});
	});
}

function StartOwnerSignup() {
	var postargs = new Object();
	var form = "ownerRegister".getid();
	//alert(form);
	postargs.fname_owner = form.fname_owner.value;
	postargs.lname_owner = form.lname_owner.value;
	postargs.company_owner = form.company_owner.value;
	postargs.address1_owner = form.address1_owner.value;
	postargs.address2_owner = form.address2_owner.value;
	postargs.city_owner = form.city_owner.value;
	postargs.stateorprovince_owner = form.stateorprovince_owner.value;
	postargs.zip_owner = form.zip_owner.value;
	postargs.province_owner = form.province_owner.value;
	postargs.country_owner = form.country_owner.value;
	
	postargs.phone_owner = form.phone_owner.value;
	postargs.uname_owner = form.uname_owner.value;
	postargs.upass_owner = form.upass_owner.value;
	if (form.rememberMe_owner.checked) {
		postargs.rememberMe_owner = "Yes";
	} else {
		postargs.rememberMe_owner = "No";
	}
	
	$("#statusLine").hide();
	$("#statusLine").load("ownersignup.php",postargs,function(resp, status, obj) {
		if (status != 'success') alert(status);
		
		hideoverlays();
	});
}

function ShowFormFields(form) {
	var inputs = $(form+' :input');
	var len = inputs.length;
	var s;
	s = ":";
	for (i = 0; i < len; i++) {
		var obj = inputs[i];
		var name = obj.name;
		var val = obj.value;
		s += name+"="+val+":";
	}
	alert(s);
}

function OpenAddListing() {
	hideoverlays();
	
	showoverlay('addListingLayer');
	$('#addListingBox').show();
	
	$('#addListing').validate({
		wrapper: 'p',
		focusCleanup: true,
		rules: {
			rent: { required: true },
			comments: { required: true },
			address_owner: { required: true },
			city_owner: { required: true },
			zip_owner: { required: true, ZIP: true} ,
			phone_owner: { required: true, phone: true} ,
			email_owner: { required: true, email: true }
		},
		messages: {
			rent: "Please enter the rent",
			comments: "Please enter a description",
			address_owner: "Please enter the street address of the new listing",
			city_owner: "Please enter the city or town of the new listing",
			zip_owner: { required: "Please enter the ZIP code of the new listing", ZIP: "Please enter a 5 or 9 digit ZIP code" },
			phone_owner: { required: "Please enter the telephone number of the owner", phone: "Please enter a valid phone number" },
			email_owner: { required: "Please enter the email address of the owner", email: "Please enter a valid email address" }
		}
	});

	//$('#addListingSubmit').click(function() {
		//alert("start add listing process");
		//ShowFormFields('#addListing');
	//});

	$('#cancelUpload').click(function() {
		CloseAddListing();
		return false;
	});
}

function CloseAddListing() {
	hideoverlays();
	activeoverlay = "";
	return false;
}

function hold(msg) {
	// this is a placeholder for hrefs to locations that haven't been done yet
	// in the anchor (or form) you should put href='JavaScript:hold()' (or action=... in forms), with an optional string as an argument
	//   if you want it to pop up an alert box containing that message (e.g. a call to hold('hello') will pop up an alert that says hello).
	// the actual link (returned by this function) will be '#', which will leave the user at the same location that he's currently at
	// ...
	// later on, you can replace the call to hold() with a call to the correct JS action routine, after it has been written
	if (msg != null) {
		alert(msg);
	}
	//return false;
}

// Mass transit utility

var geocoder ;
var reasons = [ ] ;
var accuracy = [ ] ;

function FindNearestSubway(address, aptID) {
	//MetersToMiles = /*meters to inches*/39.37 / /*inches to feet*/12 / /*feet to miles*/5280;
	//alert("FindNearestSubway("+address+","+aptID+")");
	args = new Object();
	args.aptID = aptID;
	geocoder.getLatLng(address, function (result) {
		if (result != null) {
			//alert(result.toSource());
			var posn = new LatLng(result.lat(),result.lng());
			//alert(posn.toSource());
			for (i = 0; i < bostonsubway.length; i++) {
				station = bostonsubway[i];
				//alert(station.toSource());
				//alert(posn.distM);
				dist = posn.distM(new LatLng(station.lat,station.lng));
				//alert("dist = "+dist);
				//dist = dist.toFixed(1);
				if (args.dist && dist >= args.dist) continue;
				args.dist = dist;
				dist = Math.round(dist*10)/10;
				args.result = station.name + "(" + station.line + ") " + dist + " miles";
			}
			
			//alert(args.toSource());
			
			args.lat = result.lat();
			args.lng = result.lng();
			
			publictransit = args.result;
			$("#nearestsubway").html(args.result);

			$("#statusline").load("updatelistingsubway.php",args,function(resp,status,obj) {
				if (status != "success") {
					alert(status);
				}
			});
			//alert("result = "+args.result);
			// return args.result;
		} else {
			//alert("null result from geocoder");
			// return "[Address not found]";
		}
	});
}

// contents of searchresults.js

// sort utilities

function sortbyrownumasc(lhs, rhs) {
	if (Number(lhs[0]) < Number(rhs[0])) return -1;
	if (Number(lhs[0]) > Number(rhs[0])) return  1;
	return 0;
}

function sortbyrownumdesc(lhs, rhs) {
	return sortbyrownumasc(rhs, lhs);
}

function sortbyrentasc(lhs, rhs) {
	if (Number(lhs[6]) < Number(rhs[6])) return -1;		// lhs[6] = rent
	if (Number(lhs[6]) > Number(rhs[6])) return  1;

	return sortbyrownumasc(lhs, rhs);
}

function sortbyrentdesc(lhs, rhs) {
	return sortbyrentasc(rhs, lhs);
}

function sortbybedroomsasc(lhs, rhs) {
	if (lhs[5] < rhs[5]) return -1;		// lhs[5] = bedrooms
	if (lhs[5] > rhs[5]) return  1;

	return sortbyrownumasc(lhs, rhs);
}

function sortbybedroomsdesc(lhs, rhs) {
	return sortbybedroomsasc(rhs, lhs);
}

function sortbyaddressasc(lhs, rhs) {
	if (lhs[4] < rhs[4]) return -1;		// lhs[4] = state
	if (lhs[4] > rhs[4]) return  1;
	if (lhs[3] < rhs[3]) return -1;		// lhs[3] = city
	if (lhs[3] > rhs[3]) return  1;
	if (lhs[2] < rhs[2]) return -1;		// lhs[2] = area
	if (lhs[2] > rhs[2]) return  1;

	return sortbyrownumasc(lhs, rhs);
}

function sortbyaddressdesc(lhs, rhs) {
	return sortbyaddressasc(rhs, lhs);
}

function sortbydateenteredasc(lhs, rhs) {
	if (lhs[1] < rhs[1]) return -1;		// lhs[1] = dateentered
	if (lhs[1] > rhs[1]) return  1;

	return sortbyrownumasc(lhs, rhs);
}

function sortbydateentereddesc(lhs, rhs) {
	return sortbydateenteredasc(rhs, lhs);
}

function sortbydateavailableasc(lhs, rhs) {
	if (lhs[9] < rhs[9]) return -1;		// lhs[9] = dateavailable
	if (lhs[9] > rhs[9]) return  1;

	return sortbyrownumasc(lhs, rhs);
}

function sortbydateavailabledesc(lhs, rhs) {
	return sortbydateavailableasc(rhs, lhs);
}

var monthnames = new Array("", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

function formatdate(s) {
    var a = s.split("-");
    return Number(a[2])+"-"+monthnames[Number(a[1])]+"-"+Number(a[0]);    
}

// to sort the search results, call searchresults.sort(f), where f is the name of one of the sorting
// functions defined above

var headings = new Array("Price", "Bedrooms", "Address", "Listed", "Available");
var cols = new Array(6, 5, 4, 1, 9);
var widths = new Array('25%', '20%', '25%', '15%', '15%');

function searchheader(i) {
	var s = headings[i];
	var c = "";

    if (prevsortby == cols[i]) {
        if (prevsortdir == 0) {
            //s += "&darr;";
            c = "desc";
        } else {
            //s += "&uarr;";
            c = "asc";
        }
    }
    if (c == "") {
		s = s.href('JavaScript:reordersearch('+i+')').a().width(widths[i]).height('33').th().crlf();
    } else {
		s = s.href('JavaScript:reordersearch('+i+')').a().width(widths[i]).height('33').cls(c).th().crlf();
    }
    return s;
}

function populateresults() {
	if (searchcount <= 0) return;
	
	var div = "resultTable".getid();
    // the TDs in TR[0] are in the following order:
    // 0: details link & image
    // 1: bedrooms
    // 2: address (area, city, state)
    // 3: dateentered (+ new listing)
    // 4: dateavailable (+ hotlist link if user is logged in)
    // the TDs in TR[1] are:
    // 0: rent
    // the TDs in TR[2] are:
    // 0: details link
    //alert("sortby = "+prevsortby+", sortdir = "+prevsortdir);
    var s = "";
    s += searchheader(0);
    s += searchheader(1);
    s += searchheader(2);
    s += searchheader(3);
    s += searchheader(4);
    s = s.tr().thead().crlf();
    var body = "";
    for (i = 0; i < searchcount; i++) {
		var row = "";
		
        var listing = searchresults[i];
		var picarray = listing[8];
		var s1 = "new Array(\""+picarray.join("\",\"")+"\")";
		s1 = s1+",\""+listing[10]+"\","+i+","+listing[7];
		
		var cell1 = "";
		if (picarray.length == 0) {
	        cell1 = "".src(blankimg).alt('image of: No Photo Available').cls('table').img().href('JavaScript:CreateDetailLayer('+listing[7]+')').a();
		} else {
			if (utype != 'A') { 
			cell1 = "".src(picarray[0]).alt('image of: apartment').cls('table').img().href('JavaScript:populateimages('+s1+");").a(); 
			} else {
	        cell1 = "".src(picarray[0]).alt('image of: apartment').cls('table').img().href('JavaScript:openCapture()').a();
			}
		}
		row += cell1.width(widths[0]).cls('firstRow').id('sranchor'+i).td().crlf();
        var cell2 = listing[5].p();
		if (client > 0) {
			cell2 += listing[10].p();
		}
		row += cell2.width(widths[1]).cls('firstRow').td().crlf();
		var cell3 = "";
		if (listing[2] != "") {
			cell3 = listing[2].p();
		}
        cell3 += listing[3].p()+listing[4].p();
		row += cell3.width(widths[2]).cls('firstRow').td().crlf();
		var cell4 = formatdate(listing[1]).p();
        if (listing[1] >= searchnewlistingdate) {
            cell4 += "New listing".p();
        }
		row += cell4.width(widths[3]).cls('firstRow').td().crlf();
		var cell5 = formatdate(listing[9]).p();
		row += cell5.width(widths[4]).cls('firstRow').td().crlf();
		body += row.tr();

        cell1 = ('$'+listing[6]).h2();
		row = cell1.width(widths[0]).height('10').td().crlf();
		row += "".width(widths[1]).height('10').td().crlf();
		row += "".width(widths[2]).height('10').td().crlf();
		row += "".width(widths[3]).height('10').td().crlf();
		row += "".width(widths[4]).height('10').td().crlf();
		body += row.tr();
		
		if (mode == "start") {
		cell1 = "Details".href('JavaScript:CreateDetailLayer('+listing[7]+'); _gaq.push("/Registration/detailsLink")').a().h2();
		} else {
			cell1 = "Details".href('JavaScript:CreateDetailLayer('+listing[7]+')').a().h2();
		} 
		if (searchmode == "hotlist") {
			cell1 += "Remove from Showing List".href('Javascript:RemoveFromHotlist('+listing[7]+')').a().h2();
		} else {
			cell1 += "Request a Showing".href('Javascript:AddToHotlist('+listing[7]+')').a().h2();
        }
		row = cell1.width(widths[0]).height("10").cls('lastRow').td().crlf();
		row += "".width(widths[1]).height("10").cls('lastRow').td().crlf();
		row += "".width(widths[2]).height("10").cls('lastRow').td().crlf();
		row += "".width(widths[3]).height("10").cls('lastRow').td().crlf();
		row += "".width(widths[4]).height("10").cls('lastRow').td().crlf();
		body += row.tr();
    }
    s += body.tbody().crlf();
    div.innerHTML = s.width("100%").id("srchrslts").table();
	

//	var img = root+'image/th_bg.png';
//	$('th').css('background-image','url('+img+')');
//
//	img = root+'image/th_bg_up.png';
//	$('th.asc').css('background-image','url('+img+')');
//
//	img = root+'image/th_bg_down.png';
//	$('th.desc').css('background-image','url('+img+')');
}

function SetBigImage(pic) {
	$("#largeImg").attr({ src: pic });
	//return false;
}

function populateimages(picarray, street, ndx, aptID) {
	var lim = picarray.length;

	var s = "";
	if (lim > 7) lim = 7;
	for (i = 1; i <= lim; i++) {
		//if (browser == "IE") {
		//if (browser == "Mozilla" && Number(browserversion) <= 4.0) {
		if (browser == "MSIE") {
			s += "".src(picarray[i-1]).alt('Image '+i).width('32').height('24').img().href(picarray[i-1]).title('Image '+i).a().li();
		} else {
			s += "".src(picarray[i-1]).alt('Image '+i).img().href(picarray[i-1]).title('Image '+i).a().li();
		}
	}
	'imageThumbs'.getid().innerHTML = s.cls('thumbs').ul();

	var bigimg = "largeImg".getid();
	bigimg.src = (lim == 0)? blankimg: picarray[0];
	var bigimga = "largeImgA".getid();
	bigimga.href = (lim == 0)? blankimg: picarray[0];
	var pst = "street".getid();
	pst.innerHTML = street;
	
	//$('#imageLayer').show();
	showoverlay('imageLayer');

	// note: these are undefined under IE
	//var width = window.innerWidth;
	//var height = window.innerHeight;
	// try another way
//	var width = document.documentElement.clientWidth;
	var height = document.documentElement.clientHeight;

//	var left = document.documentElement.scrollLeft;
	var top = document.documentElement.scrollTop;
//	var centerX = left+width/2;
//	var centerY = top+height/2;
//	var galwidth = $('#imageGallery').width();
	var galheight = $('#imageGallery').height();
//	
	var anchor = $("#sranchor"+ndx);
	var pos = anchor.offset();
	var scrbot = document.documentElement.scrollTop+document.documentElement.clientHeight;
	var scrtop = pos.top;
	if (scrtop + galheight > scrbot) scrtop = scrbot - galheight;

	//alert(height+" "+top+" "+galheight+" "+scrtop);

//	// uncomment the next two lines to reenable scrolling
////	$('#imageGallery').css('top', scrtop).css('left', (pos.left-30));
////	$('#imageGallery').css('top', scrtop+'px').css('left', (centerX-galwidth/2)+'px');
//	$('#imageGallery').css('top', scrtop+'px');
//	document.documentElement.scrollTop = scrtop;

	//if (browser == "Opera") {
	//if ($.browser.opera) {
		//alert(window.innerHeight - (($(document).height() > window.innerHeight) ? getScrollbarWidth() : 0)));
		//alert(window.innerHeight +" "+ $(document).height());
	//}
	
	$('#imageGallery').show();
	$('#imageGallery').vCenter();

	$('#dtlfromgallery').attr("href", 'JavaScript:CreateDetailLayer('+aptID+')');

	$(".thumbs a").click(function(){
		var largePath = $(this).attr("href");
		$("#largeImg").attr({ src: largePath });
		$("#largeImgA").attr({ href: largePath });
		return false;
	});
}

function reordersearch(tag) {
    var f;
    if (tag == 0) {
        if (prevsortby == 6 && prevsortdir == 0) {
            prevsortdir = 1;
            f = sortbyrentdesc;
        } else {
            prevsortby = 6;
            prevsortdir = 0;
            f = sortbyrentasc;
        }
    } else if (tag == 1) {
        if (prevsortby == 5 && prevsortdir == 0) {
            prevsortdir = 1;
            f = sortbybedroomsdesc;
        } else {
            prevsortby = 5;
            prevsortdir = 0;
            f = sortbybedroomsasc;
        }
    } else if (tag == 2) {
        if (prevsortby == 4 && prevsortdir == 0) {
            prevsortdir = 1;
            f = sortbyaddressdesc;
        } else {
            prevsortby = 4;
            prevsortdir = 0;
            f = sortbyaddressasc;
        }
    } else if (tag == 3) {
        if (prevsortby == 1 && prevsortdir == 0) {
            prevsortdir = 1;
            f = sortbydateentereddesc;
        } else {
            prevsortby = 1;
            prevsortdir = 0;
            f = sortbydateenteredasc;
        }
    } else if (tag == 4) {
        if (prevsortby == 9 && prevsortdir == 0) {
            prevsortdir = 1;
            f = sortbydateavailabledesc;
        } else {
            prevsortby = 9;
            prevsortdir = 0;
            f = sortbydateavailableasc;
        }
    } else {
        // by default, sort by original order
        if (prevsortby == 0 && prevsortdir == 0) {
            prevsortdir = 1;
            f = sortbyrownumdesc;
        } else {
            prevsortby = 0;
            prevsortdir = 0;
            f = sortbyrownumasc;
        }
    }
    searchresults.sort(f);
    populateresults();
}

function bump(name) {
	$('#placeHolder').load("bumpcounter.php?name="+name);
}

function SearchAgain() {
}
