var iraSuite = window.iraSuite || {};
iraSuite.ajaxLib = '/wwwroot/lib/iraSuite/1.0/ajax/';

iraSuite.localStorage   = (localStorage.iraSuite   || '{}').evalJSON();
iraSuite.sessionStorage = (sessionStorage.iraSuite || '{}').evalJSON();

Event.observe(window, 'unload', function () {
	localStorage.iraSuite   = Object.toJSON(iraSuite.localStorage);
	sessionStorage.iraSuite = Object.toJSON(iraSuite.sessionStorage);
});

iraSuite.propertySlideshow = function (classid, imgNum) {
	
/*  if imgNum is passed, make that image the first image.  used from re_dishomes */
	var url= 'http://www.iraSuite.com/wwwroot/images/homes/'+classid+'_';
	var myAjax = new Ajax.Request('/wwwroot/lib/irasuite/1.0/getphotosURLs.cfm',{
		method: 'post',
		parameters: {classid:classid},
		onSuccess: function (transport) {
			eval ("var obj = "+transport.responseText);
			var a = obj.imageNums;
			var aa = [];
			var start;
			var options = {};
			if (imgNum == undefined) {
				for (var i=0; i<a.length; i++) {
					aa.push(url+a[i]+'_l.jpg');
				}
			}
			else {
				options.width = 750;
				options.height = 563;
				options.paused = true;
				for (var i=0; i<a.length; i++) {
					if (a[i]==imgNum) {
						start=i;
					}
					if (start != undefined) {
						aa.push(url+a[i]+'_l.jpg');
					}
				}
				for (var i=0; i<start; i++) {
					aa.push(url+a[i]+'_l.jpg');
				}
			}
			var captionArray = ['<table width="100%" style="font-weight:bold;font-face:verdana;font-size:18px"><tr><td width=45%>']
			
			captionArray.push(obj.address+'<br>'+obj.city);
			captionArray.push('</td><td style="text-align:center" width="10%">'+obj.price+'</td><td width="45%" style="text-align:right; padding-right:9px">');
			captionArray.push(obj.agent+'<br>'+obj.company+'</td></tr></table>');
			options.caption = captionArray.join('');
			CSI.slideshow(aa,options);
		}
	});
}

iraSuite.slideshow = function (optObj) {
	
	/* because the capitalization situation is ambiguous with these due to some of our conventions */
	if (optObj.classid) optObj.classId = optObj.classid;
	if (optObj.agentid) optObj.agentId = optObj.agentid;
	if (optObj.compid) optObj.compId = optObj.compid;
	/*  if imgNum is passed, make that image the first image.  used from re_dishomes */
	/*  check if a specifying query limiter is sent, if not, cancel, because otherwise the database will become broken */
	if (optObj.classId || optObj.agentId || optObj.compId) {
		var url= 'http://www.iraSuite.com/wwwroot/images/homes/';
		var myAjax = new Ajax.Request('/wwwroot/lib/irasuite/1.0/getPhotoInfo.cfm',{
			method: 'post',
			parameters: { action : 'getImages', classId : optObj.classId || '', agentId : optObj.agentId || '', compId : optObj.compId || '', rotateCaptions : optObj.rotateCaptions || 'false' },
			onSuccess: function (transport) {
				eval(transport.responseText);
				var sendImages = [];
				var start;
				var options = {};
				if (!optObj.startImage || !optObj.classId){
					for (var i=0; i < images.length; i++){
						sendImages.push({ src : url + images[i].classId + '_' + images[i].imgNum + '_l.jpg', caption : images[i].caption });
					}
				}
				else {
					options.paused = true;
					for (var i = 0; i < images.length; i++) {
						if (images[i].imgNum == optObj.startImage) {
							start = i;
						}
						if (start != undefined) {
							sendImages.push({ src : url + images[i].classId + '_' + images[i].imgNum + '_l.jpg', caption : images[i].caption });
						}
					}
					for (var i = 0; i < start; i++) {
						sendImages.push({ src : url + images[i].classId + '_' + images[i].imgNum + '_l.jpg', caption : images[i].caption });
					}
				}
				Object.extend(options, optObj);
				new CSI.slideshow(sendImages, options);
			}
		});
	}
}

iraSuite.openHouseSlideshow = function (optObj) {
	
	/* because the capitalization situation is ambiguous with these due to some of our conventions */
	/* and, making allowances for plural */
	if (optObj.agentid) optObj.agentIds = optObj.agentid;
	if (optObj.compid) optObj.compIds = optObj.compid;
	if (optObj.countyid) optObj.countyIds = optObj.countyid;	
	if (optObj.agentId) optObj.agentIds = optObj.agentId;
	if (optObj.compId) optObj.compIds = optObj.compId;
	if (optObj.countyId) optObj.countyIds = optObj.countyId;
	if (optObj.agentids) optObj.agentIds = optObj.agentids;
	if (optObj.compids) optObj.compIds = optObj.compids;
	if (optObj.countyids) optObj.countyIds = optObj.countyids;	
	/*  if imgNum is passed, make that image the first image. used from re_dishomes.  */
	/*  check if a specifying query limiter is sent, if not, cancel, because otherwise the database will become broken */
	if (optObj.countyIds || optObj.agentIds || optObj.compIds) {
		var url= 'http://www.iraSuite.com/wwwroot/images/homes/';
		var myAjax = new Ajax.Request('/wwwroot/lib/irasuite/1.0/getOpenHousePhotos.cfm',{
			method: 'post',
			parameters: { action : 'getImages', countyIds : optObj.countyIds || '', agentIds : optObj.agentIds || '', compIds : optObj.compIds || '' },
			onSuccess: function (transport) {
				eval(transport.responseText);
				var sendImages = [];
				var start;
				var options = {};
			/* if (!optObj.startImage || !optObj.classId){ */
					for (var i=0; i < images.length; i++){
						sendImages.push({ src : url + images[i].classId + '_' + images[i].imgNum + '_l.jpg', caption : images[i].caption });
					}
			/* } */
				Object.extend(options, optObj);
				new CSI.slideshow(sendImages, options);
			}
		});
	}
}

iraSuite.getCities = function (optObj) {
	
	var optObj          = optObj || {};
	optObj.onSuccess    = optObj.onSuccess || function () {};
	optObj.initCounties = optObj.initCounties || '1,2,3'; /* Midland, Bay, Saginaw */
	
	/* ajax to get list of cities to search within */
	var getCities = new Ajax.Request(iraSuite.ajaxLib + 'getCities.cfm', {
		method: 'post'
		,parameters: {
			counties: optObj.initCounties
		}
		,onComplete: function (transport) {
			/* evaluate before returning transport.responseText */
			var results = eval(transport.responseText);
			optObj.onSuccess(results);
		}
	});
	
	return getCities;
}

iraSuite.featuredSlideshow = function (optObj) {
	
	/* because the capitalization situation is ambiguous with these due to some of our conventions */
	/* and, making allowances for plural */
	if (optObj.agentid) optObj.agentIds = optObj.agentid;
	if (optObj.compid) optObj.compIds = optObj.compid;
	if (optObj.countyid) optObj.countyIds = optObj.countyid;	
	if (optObj.agentId) optObj.agentIds = optObj.agentId;
	if (optObj.compId) optObj.compIds = optObj.compId;
	if (optObj.countyId) optObj.countyIds = optObj.countyId;
	if (optObj.agentids) optObj.agentIds = optObj.agentids;
	if (optObj.compids) optObj.compIds = optObj.compids;
	if (optObj.countyids) optObj.countyIds = optObj.countyids;	
	/*  if imgNum is passed, make that image the first image. used from re_dishomes.  */
	/*  check if a specifying query limiter is sent, if not, cancel, because otherwise the database will become broken */
	if (optObj.countyIds || optObj.agentIds || optObj.compIds) {
		var url= 'http://www.iraSuite.com/wwwroot/images/homes/';
		var myAjax = new Ajax.Request('/wwwroot/lib/irasuite/1.0/getFeaturedListings.cfm',{
			method: 'post',
			parameters: { action : 'getImages', countyIds : optObj.countyIds || '', agentIds : optObj.agentIds || '', compIds : optObj.compIds || '', randomize : true, daysback : optObj.daysback || '', minPrice : optObj.minPrice || '' },
			onSuccess: function (transport) {
				eval(transport.responseText);
				var sendImages = [];
				var start;
				var options = {};
			/* if (!optObj.startImage || !optObj.classId){ */
					for (var i=0; i < images.length; i++){
						sendImages.push({ src : url + images[i].classId + '_' + images[i].imgNum + '_l.jpg', caption : images[i].caption });
					}
			/* } */
				Object.extend(options, optObj);
				new CSI.slideshow(sendImages, options);
			}
		});
	}
}

/*
 * Added September 20th 2011 by Kevin J. Gay
 * sample file location : /wwwroot/lib/irasuite/samplelogin.cfm
 * 
 * */
iraSuite.createLogin = function (optObj) {
	
	var optObj      = optObj || {};
	optObj.onLogin  = optObj.onLogin  || function () {};
	optObj.onLogout = optObj.onLogout || function () {};
	
	if (iraSuite.loginObj) {
		return iraSuite.loginObj.createLink(optObj);
	};
	
	CSSRule('table.loginTable',{marginTop: '10px', width: '100%'});
	CSSRule('td input.formField',{width: '255px'});
	CSSRule('table.loginTable td.label',{fontWeight: 'bold',fontSize: '11px',paddingRight: '15px'});
	CSSRule('table.loginTable input.pass',{width:'200px'});
	CSSRule('.getpass',{fontSize: '10px', color: 'blue', cursor: 'pointer'});
	CSSRule('.cancelBtn',{marginRight: '10px', color: 'gray', cursor: 'pointer'});
	CSSRule('.loginBtn',{marginTop: '10px'});
	CSSRule('.error',{color: '#2A3E45 !important',border: '1px solid red', padding: '5px', background: '#FFEBE8'});
	
	var formObj = {
		shadowWidth: 0
		,shadowOpacity: 25
		,noFooter: true
		,overlay : {
			color: '#0b2a32'
			,opacity: 33
		}
		,closeImgStyle : {
			margin: '2px 0px 0px 10px'
		}
		,style : {
			border: '1px solid #0b2a32'
			,background: '#EFF5F7'
			,MozBorderRadius: '4px'
			,borderRadius: '4px'
			,WebkitBorderRadius: '4px'
		}
		,headerStyle : {
			color: '#0b2a32'
			,background: 'url(/wwwroot/lib/irasuite/1.0/images/grad.png) repeat-x'
			,MozBorderRadius: '4px 4px 0px 0px'
			,borderRadius: '4px 4px 0px 0px'
			,WebkitBorderRadius: '4px 4px 0px 0px'
		}
		,bodyStyle : {
			color: '#2A3E45'
			,fontSize: '12px'
		}
	}
	
	/* log in form */
	var loginFormDiv = $(document.createElement('div'));
	loginFormDiv.innerHTML = [
		,'<div></div><form>'
		,'<table class="loginTable" border="0" cellspacing="0" cellpadding="0"><tbody>'
		,'<tr height="40">'
		,'<td class="label" align="right">Email:</td><td>'
		,'<input type="text" name="email" class="formField" />'
		,'</td></tr><tr>'
		,'<td class="label" align="right">Password:</td><td>'
		,'<input type="password" name="password" class="formField" />'
		,'</td></tr><tr>'
		,'<td></td>'
		,'<td valign="top">'
		,'<span class="getpass">Forgot password?</span>'
		,'</td></tr><tr>'
		,'<td></td>'
		,'<td align="right">'
		,'<span class="cancelBtn" title="Cancel">Cancel</span>'
		,'<input type="button" name="loginBtn" class="loginBtn" value="Login" /></td>'
		,'</tr></tbody></table></form>'
	].join('');
	
	var loginObj  = iraSuite.loginObj  = createForm(formObj);
	var loginForm = loginObj.loginForm = loginFormDiv.down('form');
	loginObj.setTitle('Log in / register');
	loginObj.formBody.appendChild(loginFormDiv);
	Event.observe(loginFormDiv.down('span.cancelBtn'), 'click', loginObj.close);
	
	
	/* registration form */
	var regFormDiv = $(document.createElement('div'));
	regFormDiv.innerHTML = [
		'<div style="margin-top:10px;"></div><form>'
		,'<table class="loginTable" border="0" cellspacing="0" cellpadding="0"><tbody>'
		,'<tr><td></td>'
		,'<td align="right">'
		,'<span class="cancelBtn" title="Cancel">Cancel</span>'
		,'<input type="button" name="registerBtn" value="Create Account" /></td>'
		,'</tr></tbody></table></form>'
	].join('');
	
	var regObj  = loginObj.regObj  = createForm(formObj);
	var regForm = loginObj.regForm = regFormDiv.down('form');
	regObj.setTitle('Register');
	regObj.formBody.appendChild(regFormDiv);
	
	
	/* Reset password form - Send Email */
	var resetPassDiv = $(document.createElement('div'));
	resetPassDiv.innerHTML = [
		'<div style="margin-top:10px;"></div><form>'
		,'<div style="text-align:right;">'
		,'<span class="cancelBtn" title="Cancel">Cancel</span>'
		,'<input type="button" name="resetPassBtn" value="Send" />'
		,'<input type="button" name="ok" value="Ok" style="display:none;" />'
		,'</div></form>'
	].join('');
	
	var resetObj  = loginObj.resetObj  = createForm(formObj);
	var resetForm = loginObj.resetForm = resetPassDiv.down('form');
	resetObj.setTitle('Forgot your password?');
	resetObj.formBody.appendChild(resetPassDiv);
	Event.observe(resetPassDiv.down('span.cancelBtn'), 'click', resetObj.close);
	Event.observe(resetForm.ok, 'click', function () {
		iraSuite.loginObj.resetObj.close();
		overlayArray.each(function (obj) {
			obj.close();
		});
	});
	
	/* key expired form */
	var expiredDiv = $(document.createElement('div'));
	expiredDiv.innerHTML = [
		'<div style="margin:10px 0px 15px 0px;" class="error">'
		,'<b>The reset link that you clicked is no longer valid.</b><br />'
		,'If you still need to reset your password, you will need to <a href="javascript:void(0);">request a new link</a>'
		,'</div><form>'
		,'<div style="text-align:right;">'
		,'<input type="button" name="ok" value="Ok" />'
		,'</div></form>'
	].join('');
	
	var expObj  = loginObj.expObj  = createForm(formObj);
	var expForm = loginObj.expForm = expiredDiv.down('form');
	expObj.setTitle('Key expired!');
	expObj.formBody.appendChild(expiredDiv);
	Event.observe(expForm.ok, 'click', function () {
		iraSuite.loginObj.expObj.close();
		overlayArray.each(function (obj) {
			obj.close();
		});
	});
	Event.observe(expiredDiv.down('a'), 'click', function () {
		iraSuite.loginObj.expObj.close();
		overlayArray.each(function (obj) {
			obj.close();
		});
		var email = location.href.getUrlParms().email;
		iraSuite.loginObj.resetPassword.bind({email:email})();
	});

	
	/* change password form - Change password */
	var changePassDiv = $(document.createElement('div'));
	changePassDiv.innerHTML = [
		'<div style="margin-top:10px;"></div><form>'
		,'<table class="loginTable"></tbody>'
		,'<tr><td class="label">'
		,'<div style="text-align:right">Password:</div></td><td>'
		,'<input type="password" name="pass1" class="pass" />'
		,'</td></tr><tr><td class="label">'
		,'<div style="text-align:right">Verify Password:</div></td><td>'
		,'<input type="password" name="pass2" class="pass" />'
		,'</td></tr></tbody></table>'
		,'<div style="text-align:right;">'
		,'<input type="button" name="changePassBtn" value="Reset" />'
		,'</div></form>'
	].join('');
	
	var changeObj  = loginObj.changeObj  = createForm(formObj);
	var changeForm = loginObj.changeForm = changePassDiv.down('form');
	changeObj.setTitle('Reset password');
	changeObj.formBody.appendChild(changePassDiv);
	
	/* init loggedIn property of loginObj to false 
	 * linksArray keeps track of all links created by iraSuite.createLogin
	 * */
	loginObj.loggedIn   = false;
	loginObj.linksArray = [];
	
	/* loginObj Methods
	 * 
	 * ----------------
	 * open            
	 * onEnterKey
	 * testLogin	   
	 * login	   
	 * logout	   
	 * register	   
	 * resetPassword
	 * validateFields
	 * ----------------
	 * 
	 * */
	Object.extend(loginObj, {
		
		/* Open login form
		 * uses createForm method .show() and performs some extra operations.
		 * 
		 * */
		open : function (optObj) {
			
			if (optObj) {
				loginObj.onLogin  = optObj.onLogin  || function () {};
				loginObj.onLogout = optObj.onLogout || function () {};
			}
			var user   = iraSuite.localStorage.user;
			
			loginFormDiv.down().innerHTML = '';
			loginFormDiv.down().className = '';
			
			/* show login form */
			loginObj.show().center();			
			
			/* make sure password field is cleared */
			loginForm.password.value = '';
			
			/* auto-fill email field */
			if (user && user.email) {
				loginForm.email.value = user.email;
				loginForm.password.focus();
			}
			/* no email stored, focus email field */
			else {
				loginObj.focus();
			}
		}
		
		/* Check fields for valid email and pass
		 * if Okay - proceed to try and log user in
		 * if Bad  - display appropriate error message
		 * 
		 * */
		,onEnterKey : function () {
			if (loginObj.validateFields()) {
				loginObj.testLogin();
			}
		}
		
		/* Try loggin user in with the supplied email and password
		 * check for properly filled out fields
		 * depending on the loginRegister.cfm response, testLogin will call --
		 * 
		 * response "login"           : loginObj.login(userData); userData {email: 'user@site.com', pass: 'string'};
		 * response "register"        : loginObj.register();
		 * response "invalidPassword" : Prompt user to re-enter password
		 * 
		 * */
		,testLogin : function () {
			
			var user     = iraSuite.localStorage.user;
			var email    = loginForm.email.value;
			var password = loginForm.password.value;
			
			new Ajax.Request(iraSuite.ajaxLib + 'loginRegister.cfm', {
				method : 'post'
				,parameters : {
					action    : 'testLogin'
					,email    : email
					,password : password
				}
				,onSuccess : function (transport) {
					
					var response = eval(transport.responseText)[0];
					var action   = response.action;
					
					/* Valid email and password, sign user in */
					if (action === 'login') {
						
						loginObj.login({
							email      : email
							,password  : password
						});
					}
					/* Email isnt registered, register user */
					else if (action === 'register') {
						
						if (user && user.email && user.password) {
							delete user.password;
							return;
						}
						
						regFormDiv.down().innerHTML = '<b>Please confirm</b> that you want to create a new account for<br /><u>' + email + '</u>';
						regObj.show().center();
					}
					/* valid email address, invalid password */
					else if (action === 'invalidPassword') {
						loginFormDiv.down().className = 'error';
						loginFormDiv.down().innerHTML = 'Password is incorrect.';
						loginForm.password.select();
					}
				}
			});
		}
		
		/* Login information was good
		 * store users email and pass in localStorage
		 *   - keep a pointer to the user data in loginObj.user
		 * 
		 * */
		,login : function (userData) {

			loginObj.loggedIn = true;
			
			loginObj.user = {
				email      : userData.email
				,password  : userData.password
			}
			iraSuite.localStorage.user = loginObj.user;
			
			/* update any links associated with iraSuite.loginObj */
			loginObj.linksArray.each(function (lnk) {
				lnk.showLogout();
			});

			loginObj.close();
			loginObj.onLogin();
			
			return true;
		}
		
		,logout : function () {
			
			var user = iraSuite.localStorage.user;

			if (user && user.password) {
				user.password = undefined;
				loginObj.user.password = undefined;
			}
			loginObj.loggedIn = false;

			/* update any links associated with iraSuite.loginObj */
			loginObj.linksArray.each(function (lnk) {
				lnk.showLogin();
			});
			
			loginObj.onLogout();
		}
		
		,register : function () {
			
			if (loginObj.validateFields()) {
				
				var email    = loginForm.email.value;
				var password = loginForm.password.value
				
				new Ajax.Request(iraSuite.ajaxLib + 'loginRegister.cfm', {
					method : 'post'
					,parameters : {
						action    : 'register'
						,email    : email
						,password : password
					}
					,onSuccess : function (transport) {
						
						var response = eval(transport.responseText)[0];
						if (response.action == 'created') {
							
							regObj.close();
							
							iraSuite.loginObj.login({
								email     : this.email
								,password : this.password
							});
						}
					}.bind({email:email,password:password})
				});
			}
		}
		
		,resetPassword : function () {
			
			/* reset users password, send them confirmation email */
			var email = this.email || loginForm.email.value;

			var msg = loginFormDiv.down();
			
			if (!testEmail(email)) {
				msg.innerHTML = 'Please enter a valid email address';
				msg.className = 'error';
				return;
			} else {
				msg.innerHTML = '';
				msg.className = '';
			}

			new Ajax.Request(iraSuite.ajaxLib + 'resetPass.cfm', {
				method : 'post'
				,parameters : {
					action : 'checkEmail'
					,email : email
				}
				,onComplete : function (transport) {
					
					var response = eval(transport.responseText)[0];
					var action   = response.action;
					
					resetObj.setTitle('Forgot your password?');
					
					/* email exists, prompt user to send or cancel */
					if (action == 'exists') {
						
						resetPassDiv.down('input').show();
						resetPassDiv.down('span.cancelBtn').show();
						//resetPassDiv.down('div').innerHTML = 'Send a reset password link to: <b>' + email + '</b> ?<br /><br />';
						resetPassDiv.down('div').innerHTML = 'Click "Send" to have a an email sent to <b>' + email + '</b><br />with instructions for resetting your password.<br /><br />';
						resetForm.ok.hide();

						$(resetForm.resetPassBtn).stopObserving('click');
						resetObj.onEnterKey = function () {
							
							var loc = location.href;
							
							new Ajax.Request(iraSuite.ajaxLib + 'resetPass.cfm', {
								method : 'post'
								,parameters : {
									action : 'sendResetKey'
									,email : email
									,loc   : loc
								}
								,onComplete : function (transport) {
									
									var response = eval(transport.responseText)[0];
									var action   = response.action;
									
									/* reset password email has been sent */
									if (action === 'sent') {
										
										resetObj.setTitle('Sent!');
										resetPassDiv.down().innerHTML  = 'An email has been sent to <b>' + email + '</b><br />with instructions for resetting your password.<br /><br />';
										resetPassDiv.down('input').hide();
										resetPassDiv.down('span.cancelBtn').hide();
										resetForm.ok.show();
										resetObj.center();
										
										/* store the reset key in iraSuite.localStorage */
										iraSuite.localStorage.user.email = email;
										
										/* extend iraSuite.localStorage into localStorage
										 * - this is Not done automatically if the page is not closed or refreshed 
										 * */
										var tmp = localStorage.iraSuite.evalJSON();
										Object.extend(tmp, iraSuite.localStorage);
										localStorage.iraSuite = Object.toJSON(tmp);
									}
								}
							});
						}
						Event.observe(resetForm.resetPassBtn, 'click', resetObj.onEnterKey);
						resetObj.show().center();
						
					}
					/* Tried to reset password with an email address that isn't on record */
					else {
						msg.innerHTML = 'Unknown email address.<br />Enter a password and click "Login" to sign up.';
						msg.className = 'error';
					}
				}
			});
		}
		
		,validateFields : function () {
			
			var msg = loginFormDiv.down();
			msg.innerHTML = '';
			
			var valid    = true;
			var email    = loginForm.email.value;
			var password = loginForm.password.value;

			/* check for invalid email */
			if (!testEmail(email)) {
				valid = false;
				msg.innerHTML = 'Enter a valid email address.<br />';
			};

			/* check for password */
			if (!password.length) {
				valid = false;
				msg.innerHTML += 'Please enter a password.';
			}
			
			if (!valid) {
				msg.className = 'error';
			} else {
				msg.className = '';
			}
			
			return valid;
		}
		
		,createLink : function (optObj) {
			
			var optObj = optObj || {};
			
			var lnkStyle = {
				fontSize: '13px'
				,fontFamily: 'Arial,Helvetica,Sans-Serif'
			};
			Object.extend(lnkStyle, optObj.style || {});
			
			var loginDiv = $(document.createElement('div'));
			loginDiv.style.display = 'inline-block';
			
			var loginLnk = $(document.createElement('a'));
			loginLnk.innerHTML = optObj.loginText || 'Log In';
			loginLnk.title     = optObj.loginText || 'Log In';
			loginLnk.href      = 'javascript:void(0)';
			Event.observe(loginLnk, 'click', function () {
				iraSuite.loginObj.open();
			});
			
			var logoutLnk = $(document.createElement('a'));
			logoutLnk.innerHTML = optObj.logoutText || 'Log Out';
			logoutLnk.title     = optObj.logoutText || 'Log Out';
			logoutLnk.href      = 'javascript:void(0)';
			Event.observe(logoutLnk, 'click', function () {
				loginObj.logout();
			});
			
			Object.extend(loginLnk.style , lnkStyle);
			Object.extend(logoutLnk.style, lnkStyle);
			
			Event.observe(loginDiv, 'mouseup', function () {
				Object.extend(this.firstChild.style, lnkStyle);

				loginObj.onLogin  = optObj.onLogin;
				loginObj.onLogout = optObj.onLogout;
			});
			Event.observe(loginDiv, 'mouseenter', function () {
				Object.extend(this.firstChild.style, optObj.mouseOverStyle || {});
			});
			Event.observe(loginDiv, 'mouseleave', function () {
				Object.extend(this.firstChild.style, lnkStyle);
			});
			
			loginDiv.login  = iraSuite.loginObj.open;
			loginDiv.logout = iraSuite.loginObj.logout;
			
			/* remove logout link
			 * append login link
			 * set .loggedIn property to false
			 * */
			loginDiv.showLogin = function () {
				logoutLnk.remove();
				loginDiv.appendChild(loginLnk);
				loginDiv.loggedIn = false;
			}
			
			/* remove login link
			 * append logout link
			 * set .loggedIn property to true
			 * */
			loginDiv.showLogout = function () {
				loginLnk.remove();
				loginDiv.appendChild(logoutLnk);
				loginDiv.loggedIn = true;
			}
			
			if (iraSuite.loginObj.loggedIn) {
				loginDiv.appendChild(logoutLnk);
				loginDiv.loggedIn = true;
			} else {
				loginDiv.appendChild(loginLnk);
				loginDiv.loggedIn = false;
			}

			/* add to the loginObj links array */
			loginObj.linksArray.push(loginDiv);

			return loginDiv;
		}
	});
	
	/* If a user clicks cancel on the registration form
	 * add their email to the potentialShoppers table
	 * close the registration form
	 * */
	Event.observe(regFormDiv.down('span.cancelBtn'), 'click', function () {
		
		var hostname = location.hostname || location.host;
		
		new Ajax.Request(iraSuite.ajaxLib + 'loginRegister.cfm', {
			method : 'post'
			,parameters : {
				action : 'addPotentialShopper'
				,email : loginForm.email.value
				,hostname : hostname
			}
		});
		
		regObj.close();
	});
	
	Event.observe(loginForm.down('span.getpass'),  'click', loginObj.resetPassword);
	Event.observe(loginForm.loginBtn, 'click', loginObj.onEnterKey);
	Event.observe(regForm.registerBtn, 'click', loginObj.register);
	
	/* check for parameters in url, could be change pass redirect */
	var user     = iraSuite.localStorage.user;
	var urlParms = location.href.getUrlParms();
	
	if (urlParms && urlParms.key && urlParms.email) {

		var key   = urlParms.key;
		var email = urlParms.email;

		/* check for a valid reset key and expiration date  */
		new Ajax.Request(iraSuite.ajaxLib + 'resetPass.cfm', {
			method : 'post'
			,parameters : {
				action : 'checkValidReset'
				,email : email
				,k     : key
			}
			,onComplete : function (transport) {
				
				var response = eval(transport.responseText)[0];
				var action   = response.action;

				if (action == 'valid') {
					
					/* SHOW RESET PASS BOX
					 * */
					changeObj.show().center();
					
					changePassDiv.down('div').innerHTML =  'Reset password for<b> ' + email + '</b>';
					changePassDiv.down().className = '';
					
					changeForm.changePassBtn.stopObserving('click');
					changeObj.onEnterKey = function () {
						
						var valid = true;
						var pass1 = changeForm.pass1.value;
						var pass2 = changeForm.pass2.value;
						var email = urlParms.email;
						var key   = urlParms.key;
						
						/* either password field is blank */
						if (!pass1.length || !pass2.length) {
							changePassDiv.down().innerHTML = 'Missing a password.';
							valid = false;
						}
						
						/* passwords don't match */
						if (valid && pass1 != pass2) {
							changePassDiv.down().innerHTML = 'Passwords do not match.';
							valid = false;
						}
						
						if (!valid) {
							changePassDiv.down().className = 'error';
							return;
						}
						
						new Ajax.Request(iraSuite.ajaxLib + 'resetPass.cfm', {
							method : 'post'
							,parameters : {
								action : 'resetPass'
								,email : email
								,pass  : pass1
								,k     : key
							}
							,onComplete : function (transport) {
								
								changePassDiv.down().innerHTML = '';
								changePassDiv.down().className = '';
								
								var response = eval(transport.responseText)[0];
								var action = response.action;
								
								if (action === 'changed') {
									
									changeObj.close();
									
									/* log user in */
									loginObj.login({
										email : email
										,password : pass1
									})
								}
							}
						});
					};
					Event.observe(changeForm.changePassBtn, 'click', changeObj.onEnterKey);
					
				}
				else if (action === 'expired' || action === 'noMatch') {
					expObj.show().center();
				}
				else if (action === 'login') {
					/* try to log user in with user information from iraSuite.localStorage.user
					 * if optObj.autoLogin is true
					 * */
					if (optObj.autoLogin) {
						var user = iraSuite.localStorage.user;
						if (user && user.password) {
							loginForm.email.value = user.email;
							loginForm.password.value = user.password;
							
							loginObj.testLogin();
						} else {
							if (optObj.loginRequired) {
								loginObj.open();
							}
						}
						loginForm.password.value = '';
					}
				}
				
			}
		});
		
		return loginObj.createLink(optObj);
	}
	else {
		/* try to log user in with user information from iraSuite.localStorage.user
		 * if optObj.autoLogin is true
		 * */
		if (optObj.autoLogin) {
			var user = iraSuite.localStorage.user;
			if (user && user.password) {
				loginForm.email.value = user.email;
				loginForm.password.value = user.password;
				
				loginObj.testLogin();
			} else {
				if (optObj.loginRequired) {
					loginObj.open();
				}
			}
			loginForm.password.value = '';
		}
		
		return loginObj.createLink(optObj);
	}
}

/* Added August 26 2011  - Kevin J. Gay
 * sample file location : /wwwroot/lib/irasuite/samplesearchbox.cfm
 */
iraSuite.createSearchBox = function (optObj) {
	
	CSSRule('#searchTable', {fontSize: '13px', fontFamily: 'Arial,Helvetica,Sans-Serif'});
	CSSRule('#searchTable td.label', {fontWeight: 'bold', color: '#000', padding: '10px 0px 0px 0px'});
	CSSRule('.resultNum', {fontWeight: 'bold', color: '#576c86'});

	var embedDiv  = $(optObj.target);
	var wrapper   = document.createElement('div');
	var searchDiv = document.createElement('div');
	var resultDiv = document.createElement('div');
	
	resultDiv.id  = 'resultDiv';

	var searchParms = {
		minprice   : ''
		,maxprice  : ''
		,minsqfeet : ''
		,minbeds   : ''
		,minbaths  : ''
		,proptypes : []
		,counties  : []
		,cities	   : []
		,orderby   : 'price desc'
	}
	Object.extend(searchParms, localStorage.searchParms.evalJSON()); /*  extend default searchParms with localStorage.searchParms */
	localStorage.searchParms = Object.toJSON(searchParms);
	
	var loaderImg = new Image(35,35);
	loaderImg.src = '/wwwroot/lib/irasuite/1.0/images/loader.gif';
	
	var loaderDiv = $(document.createElement('div'));
	loaderDiv.style.margin = '30px auto 30px';
	loaderDiv.style.whiteSpace = 'nowrap';
	loaderDiv.style.textAlign = 'center';
	
	var loaderImgDiv = $(document.createElement('div'));
	loaderImgDiv.style.display = 'inline';
	
	var loaderTextDiv = $(document.createElement('div'));
	loaderTextDiv.style.padding  = '10px 0px 0px 0px';
	loaderTextDiv.style.fontSize = '1.4em';
	loaderTextDiv.style.color = '#294048';
	loaderTextDiv.innerHTML = '<i>Loading</i>';
	
	loaderImgDiv.appendChild(loaderImg);
	loaderDiv.appendChild(loaderImgDiv);
	loaderDiv.appendChild(loaderTextDiv);

	embedDiv.appendChild(wrapper);
	wrapper.appendChild(searchDiv);
	wrapper.appendChild(resultDiv);
	
	/*  search form */
	var iHTML = [
		'<form id="searchForm" style="margin:0px">'
		,'<table id="searchTable" border="0" cellspacing="0" cellpadding="0"><tbody><tr>'
		,'<td colspan="2" class="label">County'
		,'</td></tr><tr>'
		,'<td colspan="2" id="countySelect">'
		,'</td></tr><tr>'
		,'<td colspan="2" class="label">City'
		,'</td></tr><tr>'
		,'<td colspan="2" id="citySelect">'
		,'</td></tr><tr>'
		,'<td colspan="2" class="label">Property Type'
		,'</td></tr><tr>'
		,'<td colspan="2" id="proptypeSelect">'
		,'</td></tr><tr>'
		,'<td colspan="2" class="label">Price'
		,'</td></tr><tr>'
		,'<td colspan="2">'
		,'<div style="white-space: nowrap">'
		,'<span id="minPriceSpan">'
		,'</span>'
		,'<div style="display:inline;margin:0px 3px;">to</div>'
		,'<span id="maxPriceSpan">'
		,'</span>'
		,'</div>'
		,'</td></tr><tr>'
		,'<td colspan="2" class="label" style="white-space:nowrap">'
		,'<span style="width:83px;display:inline-block;">Beds</span>'
		,'<span style="display:inline;">Baths</span>'
		,'</td></tr><tr>'
		,'<td colspan="2">'
		,'<div style="white-space:nowrap">'
		,'<select id="minBeds" name="minBeds" style="width: 68px">'
		,'<option value="0" selected="selected">Any</option>'
		,'<option value="1">1+</option>'
		,'<option value="2">2+</option>'
		,'<option value="3">3+</option>'
		,'<option value="4">4+</option>'
		,'<option value="5">5+</option>'
		,'</select>'
		,'<select id="minBaths" name="minBaths" style="width: 68px;margin-left:14px;">'
		,'<option value="0" selected="selected">Any</option>'
		,'<option value="1">1+</option>'
		,'<option value="2">2+</option>'
		,'<option value="3">3+</option>'
		,'<option value="4">4+</option>'
		,'<option value="5">5+</option>'
		,'</select>'
		,'</div>'
		,'</td></tr><tr>'
		,'<td colspan="2" class="label">Sq. Feet'
		,'</td></tr><tr>'
		,'<td colspan="2">'
		,'<select id="minSqFt" name="minSqFt">'
		,'<option selected="selected" value="0">Any</option>'
		,'<option value="250">250 +</option>'
		,'<option value="500">500 +</option>'
		,'<option value="1000">1,000 +</option>'
		,'<option value="1250">1,250 +</option>'
		,'<option value="1500">1,500 +</option>'
		,'<option value="1750">1,750 +</option>'
		,'<option value="2000">2,000 +</option>'
		,'<option value="2250">2,250 +</option>'
		,'<option value="2500">2,500 +</option>'
		,'<option value="2750">2,750 +</option>'
		,'<option value="3000">3,000 +</option>'
		,'<option value="3250">3,250 +</option>'
		,'<option value="3500">3,500 +</option>'
		,'<option value="3750">3,750 +</option>'
		,'<option value="4000">4,000 +</option>'
		,'<option value="5000">5,000 +</option>'
		,'<option value="10000">10,000 +</option>'
		,'</select>'
		,'</td></tr><tr>'
		,'<td colspan="2" valign="bottom" height="40">'
		,'<input id="searchBtn" type="button" value="Search" disabled="disabled" class="submitBtn" />'
		,'</td></tr></tbody></table></form>'
	];
	
	searchDiv.innerHTML = iHTML.join('');
	
	/*  result number Div */
	var counterDiv = $(document.createElement('div'));
	counterDiv.id = 'resultNumDiv';
	counterDiv.style.margin = '5px 0px 0px 0px';
	counterDiv.innerHTML = 'Found <span id="total" class="resultNum">...</span> results'
	
	searchDiv.insertBefore(counterDiv, searchDiv.firstChild);
	
	var minPriceInput = CSI.createPromptInput({
		name: 'minPrice'
		,prompt: 'min'
		,inputType: 'numbers'
		,inputStyle: { 
			width: '60px'
		}
		,onEvent: function () {
			$('searchBtn').setAttribute('disabled', '');
			$('searchBtn').disabled = false;
		}
	});
	
	var maxPriceInput = CSI.createPromptInput({
		name: 'maxPrice'
		,prompt: 'max'
		,inputType: 'numbers'
		,inputStyle: { 
			width: '60px'
		}
		,onEvent: function () {
			$('searchBtn').setAttribute('disabled', '');
			$('searchBtn').disabled = false;
		}
	});
	
	$('minPriceSpan').appendChild(minPriceInput);
	$('maxPriceSpan').appendChild(maxPriceInput);
	
	function setDimensions () {
		var winH = getScroll().height;
		var emDivTop  = embedDiv.viewportOffset().top;
		var emBorder  = Number(embedDiv.style.borderTopWidth) + Number(embedDiv.style.borderBottomWidth);
		var emPadding = Number(embedDiv.style.paddingTop) + Number(embedDiv.style.paddingBottom);
		var footerH   = typeof optObj.footer === 'string' ? $(optObj.footer).getHeight() : 0;

		if (optObj.footerHeight) {
			footerH = parseInt(optObj.footerHeight);
		}

		wrapper.style.height   = (winH - emDivTop - footerH) + 'px';
		searchDiv.style.height = $(wrapper).getHeight() + 'px';
		resultDiv.style.height = $(wrapper).getHeight() + 'px';
		
		if (!wrapper.dims) wrapper.dims = {resHeight : 208};
		wrapper.dims.set = Math.ceil($(wrapper).getHeight() / wrapper.dims.resHeight);

	};
	Event.observe(window, 'resize', setDimensions);
	
	function setStyles () {

		Object.extend(wrapper.style, {
			position: 'relative'
			,lineHeight: 'normal'
		});	

		var searchDivStyle = {
			width: ($('searchTable').getWidth()) + 'px'
			,padding: '0px 10px 0px 10px'
			,position: 'absolute'
			,background: '#fff'
		};
		Object.extend(searchDivStyle , optObj.searchDivStyle || {});
		Object.extend(searchDiv.style, searchDivStyle || {});

		var searchFormStyle = {
			background: '#fff'
		};
		Object.extend(searchFormStyle, optObj.searchFormStyle || {});
		Object.extend($('searchForm').style, searchFormStyle  || {});

		var resultDivStyle = {
			width: ($(wrapper).getWidth() - $(searchDiv).getWidth() - 2) + 'px'
			,cssFloat: 'right'
			,styleFloat: 'right'
			,background: '#fff'
			,borderLeft: '1px solid #bbb'
			,overflowY: 'auto'
		}
		Object.extend(resultDivStyle , optObj.resultDivStyle || {});
		Object.extend(resultDiv.style, resultDivStyle || {});
	}
	setStyles();
	setDimensions();

	function search (set) {
		
		var form     = $('searchForm');
		var minPrice = Number(form.minPrice.value);
		var maxPrice = Number(form.maxPrice.value);
		var minBeds  = Number(form.minBeds.value);
		var minBaths = Number(form.minBaths.value);
		var minSqFt  = Number(form.minSqFt.value);
		$('searchBtn').disabled = true;
		
		/*  logic for minPrice && maxPrice */
		minPrice = (minPrice == (0 || '')) ? 0         : minPrice;
		maxPrice = (maxPrice == (0 || '')) ? 999999999 : maxPrice;
		if (minPrice > maxPrice) {
			var x = minPrice;
			var y = maxPrice;
			minPrice = y;
			maxPrice = x;
		}
		
		optObj.search = localStorage.searchParms.evalJSON();
		Object.extend(optObj.search, {
			minprice   : (minPrice ? minPrice : '')
			,maxprice  : (maxPrice == 999999999 ? '' : maxPrice)
			,minbeds   : (minBeds  ? minBeds : '')
			,minbaths  : (minBaths ? minBaths : '')
			,minsqfeet : (minSqFt  ? minSqFt : '')
			,agentids  : optObj.agentids || []
			,compids   : optObj.compids  || []
			,boardids  : optObj.boardids || []
		});
		iraSuite.search.recordsToReturn = set * 3 || optObj.recordsToReturn || wrapper.dims.set * 5;
		
		Object.extend(optObj, {
			onSuccess: function (listings) {
				
				var resultDiv = $('resultDiv');
				listings.each(function (listing) {
					resultDiv.appendChild(iraSuite.createResult(listing, {
						idx : optObj.idx
						,imagePath : optObj.imagePath || false
					}));
				});
				
				$('total').innerHTML = this.totalResults;
			}
			/*  show loading animation */
			,onLoading: function () {
				resultDiv.appendChild(loaderDiv);
			}
			/*  remove loading animation */
			,onLoaded: function () {
				loaderDiv.remove();
			}
		});

		if (!set) {

			if (iraSuite.search.activeSearch) {
				iraSuite.search.activeSearch.abort();
			};

			/*  remove current results */
			$('resultDiv').childElements().invoke('remove');

			/*  reset result counter */
			$('total').innerHTML = '...';
		}

		iraSuite.search(optObj);
	}
	
	/* get agent user information if optObj.idxAgentId is not undefined */
	if (optObj.idxAgentId || optObj.idxCompId) {
		
		var paramsObj = {
			action : 'getIdxData'
		};
		
		if (optObj.idxAgentId) {
			paramsObj.idxAgentId = optObj.idxAgentId;
		} else {
			paramsObj.idxCompId = optObj.idxCompId;
		}
		
		new Ajax.Request(iraSuite.ajaxLib + 'getIdxData.cfm', {
			method : 'post'
			,parameters : paramsObj
			,onComplete : function (transport) {
				optObj.idx = eval(transport.responseText)[0];
			}
		});
	}
	
	/*  get counties and cities for select boxes / initialize search form / fire the search */
	iraSuite.getCities({
		initCounties: optObj.initCounties || ''
		,onSuccess: function (response) {
			
			var load          = true;
			var citiesRef     = [];
			var countiesArr   = [];
			var initCounties  = searchParms.counties;
			var initPropTypes = searchParms.proptypes;
			var initCities    = searchParms.cities;

			response.each(function (co) {
				/*  counties Array */
				countiesArr.push({
					text: co.county
					,value: co.county_id
					,checked: false
				});
				/*  cities reference, indexed by county_id */
				citiesRef[co.county_id] = co.cities;
			});
			
			/*  check selected counties if : not all counties are selected || more than none are selected */
			if (initCounties.length != 0 && initCounties.length != countiesArr.length) {
				countiesArr.each(function (co) {
					if (initCounties.indexOf(co.value)+1) co.checked = true;
				});
			}
			
			var countiesOpt = {
				width: '150px'
				,name: 'counties'
				,hint: 'All Counties'
				,allHint: 'All Counties'
				,formStyle: {fontSize: '1.1em',borderColor: '#717171'}
				,onClose: function () {}
				,onChange: function () {
					
					var citiesArr = [], sel = false;
					
					/*  all or none (counties) have been selected : push all values to searchParms */
					if (!this.value.length) {
						searchParms.counties = this.selected.length ? this.selected : this.unselected;
					}
					/*  some counties were selected : push values to searchParms */
					else {
						searchParms.counties = this.selected;
					}
					
					if (!load && searchParms.counties.toString() == localStorage.searchParms.evalJSON().counties.toString()) {
						return;
					}
					
					/*  loop through selected counties */
					searchParms.counties.each(function (co, i) {
						var cx, selected = 0; citiesArr[i] = [];
						
						/*  loop through counties cities */
						citiesRef[co].each(function (ci) {
							cx = false;
							
							/*  check to see if city was selected */
							if (searchParms.cities.indexOf(ci.city_id)+1) {
								sel = true;
								cx  = true;
								selected++;
							}
							
							/*  add city to the cities array */
							citiesArr[i].push({
								text: ci.city
								,value: ci.city_id
								,checked: cx
							});
						});
						
						/*  if NO cities were selected for this county : select all */
						if (!selected) {
							citiesArr[i].each(function (ci) {
								ci.checked = true;
							});
						}
					});
					
					/*  flatten multidimensional cities array (case : if multiple counties were selected) */
					citiesArr = citiesArr.flatten();
					
					/*  if one county is selected and no cities were specifically selected */
					/*  the cities will need to be set back to unchecked */
					if ((!sel && searchParms.counties.length == 1)
						|| (!sel && (searchParms.counties.length == this.length))
						|| (!sel)) {
							citiesArr.each(function(ci){
								ci.checked = false;
							});
					}
					
					/*  reset the cities multiSelect */
					citiesObj.resetOptions(citiesArr);
				}
			};
			
			var citiesOpt = {
				cols: 3
				,width: '150px'
				,name: 'cities'
				,hint: 'All Cities'
				,allHint: 'All Cities'
				,selectAll: true
				,formStyle: {fontSize: '1.1em',borderColor: '#717171'}
				,onClose:  function () {}
				,onChange: function () {
					
					if (!this.value.length) {
						searchParms.cities = [];
					} else {
						searchParms.cities = this.selected;
					}

					if ((localStorage.searchParms.evalJSON().cities.toString() != searchParms.cities.toString())
						|| (localStorage.searchParms.evalJSON().counties.toString() != searchParms.counties.toString())) {
						localStorage.searchParms = Object.toJSON(searchParms);
						if (!load) search();						
					}
				}
			};

			var propTypeArr = [
				{text: 'Single Family', value: 1233, checked: false}
				,{text: 'Condo', value: 38, checked: false}
				,{text: 'Waterfront', value: 1240, checked: false}
				,{text: 'Commercial', value: 911, checked: false}
				,{text: 'Vacant Land', value: 909, checked: false}
			];

			if (propTypeArr.length != 0 && propTypeArr.length != initPropTypes.length) {
				propTypeArr.each(function (propType) {
					if (initPropTypes.indexOf(parseInt(propType.value))+1) {
						propType.checked = true;
					}
				});
			}

			var propTypeOpt = {
				width: '150px'
				,name: 'proptypes'
				,hint: 'All Property Types'
				,allHint: 'All Property Types'
				,formStyle: {fontSize: '1.1em',borderColor: '#717171'}
				,onClose: function () {}
				,onChange: function () {
					
					if (this.value.length) {
						searchParms.proptypes = this.selected;
					} else {
						searchParms.proptypes = this.unselected.length ? this.selected : this.unselected;
					}

					if (localStorage.searchParms.evalJSON().proptypes.toString() != searchParms.proptypes.toString()) {
						localStorage.searchParms = Object.toJSON(searchParms);
						if (!load) search();						
					}
				}
			};

			countiesObj = CSI.createMultiSelect(countiesArr, countiesOpt);
			citiesObj   = CSI.createMultiSelect([], citiesOpt);
			propTypeObj = CSI.createMultiSelect(propTypeArr, propTypeOpt);
			
			countiesObj.onChange();
			
			$('countySelect').appendChild(countiesObj);
			$('citySelect').appendChild(citiesObj);
			$('proptypeSelect').appendChild(propTypeObj);
			
			initCities    = [];
			initCounties  = [];
			initPropTypes = [];
			
			searchParms.minprice == ('' || 0) ? '' : minPriceInput.setValue(searchParms.minprice);
			searchParms.maxprice == ('' || 0) ? '' : maxPriceInput.setValue(searchParms.maxprice);
			$('minBeds').value  = Number(searchParms.minbeds);
			$('minBaths').value = Number(searchParms.minbaths);
			$('minSqFt').value  = Number(searchParms.minsqfeet);
			
			search();
			load = false;
		}
	});
	
	/*  input (minPrice - maxPrice) : 'change', 'keypress' events */
	Event.observe($('minPrice'), 'change', function () {
		searchParms.minprice     = this.value;
		localStorage.searchParms = Object.toJSON(searchParms);
		search();
	});
	Event.observe($('maxPrice'), 'change', function () {
		searchParms.maxprice     = this.value;
		localStorage.searchParms = Object.toJSON(searchParms);
		search();
	});
	
	/*  minBeds 'change' : update localStorage.searchParms --> minbeds / search */
	Event.observe($('minBeds'), 'change', function () {
		searchParms.minbeds      = this.value;
		localStorage.searchParms = Object.toJSON(searchParms);
		search();
	});
	/*  minBaths 'change' : update localStorage.searchParms --> minbaths / search */
	Event.observe($('minBaths'), 'change', function () {
		searchParms.minbaths     = this.value;
		localStorage.searchParms = Object.toJSON(searchParms);
		search();
	});
	/*  minSqFt 'change' : update localStorage.searchParms --> minsqfeet / search */
	Event.observe($('minSqFt'), 'change', function () {
		searchParms.minsqfeet    = this.value;
		localStorage.searchParms = Object.toJSON(searchParms);
		search();
	});
	
	Event.observe(resultDiv, 'scroll', function () {
		
		var scrollTop = Math.ceil(this.cumulativeScrollOffset().top);
		var viewable  = Math.ceil(this.clientHeight || this.getHeight());
		var returned  = iraSuite.search.returnedResults;
		var total     = iraSuite.search.totalResults;
		
		if ((returned < total && !iraSuite.search.activeSearch)
			&& (returned < ((scrollTop + viewable) / wrapper.dims.resHeight) + wrapper.dims.set * 2)) {
				search(wrapper.dims.set);
		}
	});
	
	return wrapper;
};

iraSuite.search = function (optObj) {
	
	var optObj    = optObj || {};
	var newSearch = false;
	
	var searchParms = {
		minprice    : ''
		,maxprice   : ''
		,minsqfeet  : ''
		,minbeds    : ''
		,minbaths   : ''
		,proptypes  : []
		,counties   : []
		,cities	    : []
		,agentids   : []
		,compids    : []
		,boardids   : []
		,orderby    : 'price desc'
	};
	optObj.search = optObj.search || {};
	Object.extend(searchParms, optObj.search);
	
	/*  compare current search to last search */
	/*  if they are not equal a new search has been fired */
	if (iraSuite.search.lastSearchParms != Object.toJSON(optObj.search)) {
		newSearch = true;
		iraSuite.search.exClassids = [];
		iraSuite.search.returnedResults = 0;
	}
	iraSuite.search.lastSearchParms = Object.toJSON(optObj.search);
	
	/*  if a new search hasn't been fired and the default sort has not been changed, */
	/*  reset the max price in searchParms to the last results price */
	if (!newSearch && searchParms.orderby == 'price desc' && iraSuite.search.results.length) {
		searchParms.maxprice = iraSuite.search.results[iraSuite.search.results.length-1].price;
	}
	
	/*  set default callback if a callback is missing (throws an error) */
	optObj.onSuccess = optObj.onSuccess || function () {
		if (console) {
			console.error('iraSuite.search : an onSuccess callback function is missing.');
		}
	}
	
	var datasource = optObj.datasource || iraSuite.ajaxLib + 'searchReales.cfm';
	iraSuite.search.activeSearch = new Ajax.Request(datasource, {
		method: 'post'
		,parameters: {
			action: 'searchListings'
			,search: Object.toJSON(searchParms)
			,exClassids: Object.toJSON(iraSuite.search.exClassids)
			,recordsToReturn : iraSuite.search.recordsToReturn || 15
		}
		,onLoading: function (e) {
			if (optObj.onLoading) {
				optObj.onLoading();
			}
		}
		,onSuccess: function (e) {
			if (optObj.onLoaded) {
				optObj.onLoaded();
			}
		}
		,onComplete: function (transport) {
			
			iraSuite.search.activeSearch = false;
			var results = iraSuite.search.results = eval(transport.responseText);
			
			if (newSearch) {
				iraSuite.search.totalResults = Number(results.pop().count);
			} else {
				results.pop();
			}
			iraSuite.search.returnedResults += results.length;
			
			results.each(function (listing) {
				iraSuite.search.exClassids.push(listing.classid);
			});
			
			optObj.onSuccess.bind({
				newSearch         : newSearch
				,totalResults     : iraSuite.search.totalResults
				,returnedResults  : iraSuite.search.returnedResults
				,returnedClassids : iraSuite.search.exClassids
			})(results);
		}
	});
}


iraSuite.createResult = function (listingObj, optObj) {
	
	if (!iraSuite.createResult.styles) {
		iraSuite.createResult.styles = true;
		CSSRule('.propContainer',{background: '#EFF5F7',border: '1px solid #aaa',fontSize: '11px',fontFamily:'Verdana,Arial,Helvetica,sans-serif'});
		CSSRule('.heading',{color: '#49626C',fontWeight: 'bold'});
		CSSRule('.headingText div',{color: '#354951'});
		CSSRule('.classpropDiv',{color:'#49626C',fontWeight: 'normal', fontSize: '11px', marginRight: '5px',marginTop: '2px'});
		CSSRule('.idxlegal',{fontSize: '9px', color: '#999999',marginTop: '3px'});
		CSSRule('.compDiv', {color: '#0A2D40', background: '#fff', lineHeight: '140%'});
		CSSRule('.compName',{fontSize: '11px',fontWeight: 'bold',color: '#294048'});
		CSSRule('.show',{visibility: 'visible'});
		CSSRule('.hide',{visibility: 'hidden'});
		CSSRule('.propContainerOver',{border: '1px solid #6FA700'});
		CSSRule('.link', {color: 'blue', cursor: 'pointer'});
	}
	
	var optObj  = optObj     || {};
	var idx     = optObj.idx || false;
	var listing = listingObj;
	var company = listingObj.company;
	var agent   = listingObj.agent;
	
	if (idx) {
		var idxObj = {
			name      : ''
			,email    : ''
			,phone    : ''
			,homepage : ''
			,header   : ''
			,agentid  : false
			,compid   : ''
			,boardid  : ''
		};
		Object.extend(idxObj, idx);
		idx = idxObj;
	}

	var containerDiv = document.createElement('div');
	containerDiv.id = 'classid' + listing.classid;
	containerDiv.className = 'propContainer';
	
	Object.extend($(containerDiv).style, {
		padding: '5px'
		,margin: '5px 8px 8px 8px'
		/* ,height: '187px' */
		,lineHeight: 'normal'
		,MozBorderRadius: '3px'
		,borderRadius: '3px'
		,WebkitBorderRadius: '3px'
	});
	
	var imgDiv = document.createElement('div');
	imgDiv.className = 'propPic';
	
	Object.extend(imgDiv.style, {
		overflow: 'hidden'
		,textAlign: 'center'
		,width: '145px'
		,height: '108px'
		,MozBorderRadius: '2px'
		,borderRadius: '2px'
		,WebkitBorderRadius: '2px'
	});
	
	var cTable = document.createElement('table');
	var cTBody = document.createElement('tbody');
	cTable.setAttribute('cellspacing', 0);
	cTable.setAttribute('cellpadding', 0);
	
	cTable.appendChild(cTBody);

	var cTr = document.createElement('tr');
	cTBody.appendChild(cTr);
	var cTd01 = document.createElement('td');
	cTr.appendChild(cTd01);
	cTd01.setAttribute('valign', 'top');
	
	var cTd02 = document.createElement('td');
	cTr.appendChild(cTd02);
	cTd02.setAttribute('valign', 'top');
	cTd02.style.verticalAlign = 'top';
	cTd02.style.width = '100%';
	
	var iWrap = document.createElement('div');
	iWrap.style.cssFloat = 'left';iWrap.style.styleFloat = 'left';
	
	Object.extend(iWrap.style, {
		padding: '4px'
		,height: '108px'
		,width: '145px'
		,background: '#fff'
		,border: '1px solid #bbb'
		,MozBorderRadius: '3px'
		,borderRadius: '3px'
		,WebkitBorderRadius: '3px'
	});
	iWrap.appendChild(imgDiv);
	
	var headerDiv = document.createElement('div');
	headerDiv.style.textAlign = 'right';
	headerDiv.className = 'classpropDiv';
	headerDiv.style.cssFloat = 'right';
	headerDiv.style.styleFloat = 'right';
	
	var pDiv = document.createElement('div');
	pDiv.style.marginLeft = '5px';
	pDiv.style.cssFloat = 'left';pDiv.style.styleFloat = 'left';
	pDiv.style.fontSize = '15px';
	pDiv.style.color = '#11343E';
	pDiv.style.fontWeight = 'bold';
	
	var compDiv = document.createElement('div');
	compDiv.className = 'compDiv';
	compDiv.style.margin = '8px 0px 0px 0px';
	compDiv.style.padding = '5px 0px 5px 0px';
	compDiv.style.height = '50px';
	compDiv.style.border = '1px solid #A7B1C1';
	compDiv.style.MozBorderRadius = '3px';
	compDiv.style.borderRadius = '3px';
	compDiv.style.WebkitBorderRadius = '3px';
	
	var infoTable = $(document.createElement('table'));
	var infoTBody = document.createElement('tbody');
	infoTable.setAttribute('cellspacing', 0);
	infoTable.setAttribute('cellpadding', 0);
	infoTable.style.fontSize = '11px';
	infoTable.style.marginLeft = '5px';
	infoTable.style.display = 'inline-block';
	
	var linksDiv = document.createElement('div');
	linksDiv.style.fontSize  = '11px';
	linksDiv.style.marginTop = '4px';
	linksDiv.className = 'hide';
	
	var iTr = document.createElement('tr');
	var iTd01 = document.createElement('td');
	iTd01.setAttribute('valign', 'top');
	iTd01.style.verticalAlign = 'top';
	iTd01.width = '120';
	
	var iTd02 = document.createElement('td');
	iTd02.setAttribute('valign', 'top');
	iTd02.style.verticalAlign = 'top';
	iTd02.className = 'headingText';
	iTd02.width = '70';
	
	var iTd03 = document.createElement('td');
	iTd03.setAttribute('valign', 'top');
	iTd03.style.verticalAlign = 'top';
	iTd03.width = '60';
	
	var iTd04 = document.createElement('td');
	iTd04.setAttribute('valign', 'top');
	iTd04.style.verticalAlign = 'top';
	iTd04.className = 'headingText';
	
	var brBoth = document.createElement('br');
	brBoth.style.clear = 'both';
	
	infoTable.appendChild(infoTBody);
	infoTBody.appendChild(iTr);
	iTr.appendChild(iTd01);
	iTr.appendChild(iTd02);
	iTr.appendChild(iTd03);
	iTr.appendChild(iTd04);
	
	cTd01.appendChild(iWrap);
	cTd02.appendChild(pDiv);
	cTd02.appendChild(headerDiv);
	cTd02.appendChild(brBoth);
	
 	var myOps = {
		displayLines: 3
		,duration: 0.2
		,breakOn: 'char'
		,linkStyle: optObj.linkStyle || {color: 'blue'}
		,openStyleString: 'background-color: #fff;border-color: #A7B1C1;'
		,style: {
			fontFamily: 'Verdana,Arial,Helvetica,sans-serif'
			,backgroundColor: 'transparent'
		}
	};
	
	var desc = CSI.createHiddenTextDiv(listing.adtext || '', myOps);
	cTd02.appendChild(desc);
	desc.style.margin = '0px 0px 5px 5px';
	
 	if (Prototype.Browser.IE || Prototype.Browser.WebKit) {
		desc.style.margin = '8px 0px 7px 5px';
		if (Prototype.Browser.IE) {
			desc.style.margin = '6px 0px 5px 5px';
		}
	}
	
	cTd02.appendChild(infoTable);
	containerDiv.appendChild(cTable);
	containerDiv.appendChild(compDiv);
	containerDiv.appendChild(linksDiv);
	
	if (listing.firstimgnum !== '') {
		var propPic = new Image();
		
		if (!optObj.imagePath) {
			propPic.src = 'http://irasuite.com/wwwroot/images/homes/'+listing.classid+'_'+listing.firstimgnum+'_'+'i.jpg';
		} else {
			var imgSrc = listing.firstimgnum;
			if (!(/\.jpg$|\.jpeg|$\.png$|\.gif$/gi.test(imgSrc))) {
				imgSrc += '.jpg';
			}
			propPic.src = optObj.imagePath + imgSrc;
		}
		propPic.style.height = '115px';
		imgDiv.appendChild(propPic);
	} else {
		imgDiv.style.background = '#fff';
		imgDiv.innerHTML = '<br /><br /><center>No Image<br />Available</center>';	
	}
	
	var label = '';
	if (listing.singlefamily !== '') {
		label = 'Single Family Home';	
	}
 	if (listing.multifamily !== '') {
		if (label !== '') {
			label += ', Multi-family Home';
		} else {
			label = 'Multi-family Home';
		}
	}
	if (listing.condo !== '') {
		if (label !== '') {
			label += ', Condo';
		} else {
			label = 'Condo';
		}
	} 
	if (listing.commercial !== '') {
		if (label !== '') {
			label += ', Commercial';
		} else {
			label = 'Commercial';
		}
	}
	if (listing.vacantland !== '') {
		if (label !== '') {
			label += ', Vacant Land';
		} else {
			label = 'Vacant Land';
		}
	}
	if (listing.waterfront !== '') {
		if (label !== '') {
			label += ', Water Front';
		} else {
			label = 'Water Front';
		}
	}
	headerDiv.innerHTML = label;
	
	if (listing.price != '') {
		pDiv.innerHTML = '$'+Number(listing.price).format();
	}
	else if (listing.leaseprice != '') {
		pDiv.innerHTML = '$'+Number(listing.leaseprice).format();
	}
	
	var classIdDiv = document.createElement('div');
	var classIdNum = document.createElement('div');
	classIdDiv.className = 'heading';
	classIdDiv.innerHTML = 'IRA #';
	classIdNum.innerHTML = listing.classid;
	
	iTd01.appendChild(classIdDiv);
	iTd02.appendChild(classIdNum);
	
	var bedDiv = document.createElement('div');
	var bedsNum = document.createElement('div');
	bedDiv.className = 'heading';
	bedDiv.innerHTML = 'Bedrooms';

	if (listing.bedrooms != '') {
		bedsNum.innerHTML = listing.bedrooms;
	} else {
		bedsNum.innerHTML = '---';
	}
	iTd01.appendChild(bedDiv);
	iTd02.appendChild(bedsNum);
	
	var bathDiv = document.createElement('div');
	var bathsNum = document.createElement('div');
	bathDiv.className = 'heading';
	bathDiv.innerHTML = 'Full/Half Baths';
	
	/*  full baths */
	if (listing.bathrooms != '') {
		bathsNum.innerHTML = listing.bathrooms;
	} else {
		bathsNum.innerHTML = '---';
	}
	/*  half baths */
	if (listing.halfbaths != '') {
		bathsNum.innerHTML += ' / ' + listing.halfbaths;
	} else {
		bathsNum.innerHTML += ' / ---';
	}
	
	iTd01.appendChild(bathDiv);
	iTd02.appendChild(bathsNum);
	
	var acresDiv = document.createElement('div');
	var acresNum = document.createElement('div');
	acresDiv.className = 'heading';
	acresDiv.innerHTML = 'Acres';
	
	if (listing.acres != '') {
		acresNum.innerHTML = listing.acres;
	} else {
		acresNum.innerHTML = '---';
	}
	iTd03.appendChild(acresDiv);
	iTd04.appendChild(acresNum);
	
	var sqftDiv = document.createElement('div');
	var sqFtNum = document.createElement('div');
	sqftDiv.className = 'heading';
	sqftDiv.innerHTML = 'Sq.Ft';
	
	if (listing.sqfeet != '') {
		sqFtNum.innerHTML = listing.sqfeet;
	} else {
		sqFtNum.innerHTML = '---';
	}
	iTd03.appendChild(sqftDiv);
	iTd04.appendChild(sqFtNum);
	
	var yearBuiltDiv = document.createElement('div');
	var yearBuiltNum = document.createElement('div');
	yearBuiltDiv.className = 'heading';
	yearBuiltDiv.innerHTML = 'Built';
	
	if (listing.yearb != '' && listing.yearb != 'unkn' && listing.yearb != '0') {
		yearBuiltNum.innerHTML = listing.yearb;
	} else {
		yearBuiltNum.innerHTML = '---';
	}
	iTd03.appendChild(yearBuiltDiv);
	iTd04.appendChild(yearBuiltNum);
	
	var moreInfo = document.createElement('div');
	moreInfo.style.display = 'inline';
	moreInfo.style.cursor = 'pointer';
	moreInfo.style.margin = '0px 10px 0px 0px';
	moreInfo.title = 'Get More Information';
	
	var mailIcon = new Image(16,10);
	mailIcon.src = '/wwwroot/lib/irasuite/1.0/images/email.png';
	mailIcon.style.margin = '0px 5px -1px 0px';
	
	var moreTxt = document.createElement('span');
	moreTxt.innerHTML = 'Get More Information';
	moreTxt.className = 'link';
	
	Event.observe(moreInfo, 'mouseenter', function () {
		this.down('span').style.textDecoration = 'underline';
	});
	Event.observe(moreInfo, 'mouseleave', function () {
		this.down('span').style.textDecoration = '';
	});
	
	moreInfo.appendChild(mailIcon);
	moreInfo.appendChild(moreTxt);
	linksDiv.appendChild(moreInfo);
	
	var detailsWrap = document.createElement('div');
	detailsWrap.style.display = 'inline';
	detailsWrap.style.cursor = 'pointer';
	detailsWrap.title = 'View Details';
	
	var detailsIcon = new Image(12,15);
	detailsIcon.src = '/wwwroot/lib/irasuite/1.0/images/details.png';
	detailsIcon.style.margin = '0px 5px -3px 0px';
	
	var viewDetails = iraSuite.createInfoLnk(listing, 'View Details', idx);
	viewDetails.className = 'link';
	
	Event.observe(detailsWrap, 'mouseenter', function () {
		this.down('span').style.textDecoration = 'underline';
	});
	Event.observe(detailsWrap, 'mouseleave', function () {
		this.down('span').style.textDecoration = '';
	});
	
	detailsWrap.appendChild(detailsIcon);
	detailsWrap.appendChild(viewDetails);
	linksDiv.appendChild(detailsWrap);
	
	if (optObj.favorties) {
		var favDiv = linksDiv.appendChild(iraSuite.createFavLink());
		favDiv.style.display = 'inline';
		favDiv.style.marginLeft = '10px';
	}
	
	Event.observe(containerDiv, 'mouseenter', function () {
		linksDiv.className = 'show';
		containerDiv.addClassName('propContainerOver');
	});
	Event.observe(containerDiv, 'mouseleave', function () {
		linksDiv.className = 'hide';
		containerDiv.removeClassName('propContainerOver');
	});

	
	if (!idx) {
		
		/*  mailto popup box */
		moreInfo.mailto = {
			classid: listing.classid
			,address: listing.streetnum +' ' + listing.streetdir + ' ' + listing.streetname
			,agentname: agent.firstname + ' ' + agent.lastname
			,agentid: agent.agentuserid
		}
		
		Event.observe(moreInfo, 'click', function () {
			mailto(this.mailto.classid, this.mailto.address, this.mailto.agentname, this.mailto.agentid);
		});
		
		compDiv.style.height = '30px';
		
		var compNameDiv = document.createElement('div');
		compNameDiv.style.cssFloat = 'left';compNameDiv.style.styleFloat = 'left';
		compNameDiv.className = 'compName';
		
		var nameDiv = document.createElement('div');
		nameDiv.style.cssFloat = 'left';nameDiv.style.styleFloat = 'left';
		
		var addrDiv = document.createElement('div');
		addrDiv.style.cssFloat = 'left';addrDiv.style.styleFloat = 'left';
		addrDiv.style.width = '195px';
		addrDiv.style.marginLeft = '3px';
					
		var addressDiv = document.createElement('div');
		addressDiv.style.cssFloat = 'left';addressDiv.style.styleFloat = 'left';
		addressDiv.style.width = '195px';
		addressDiv.style.marginLeft = '3px';
		
		var workNumDiv = document.createElement('div');
		workNumDiv.style.cssFloat = 'left';workNumDiv.style.styleFloat = 'left';
		workNumDiv.style.marginLeft = '3px';
		
		var clrB1 = document.createElement('br');
		clrB1.style.clear = 'left';
		var clrB2 = document.createElement('br');
		clrB2.style.clear = 'left';
		var clrB3 = document.createElement('br');
		clrB3.style.clear = 'left';
		
		compDiv.appendChild(addressDiv);
		compDiv.appendChild(compNameDiv);
		compDiv.appendChild(clrB1);
		compDiv.appendChild(addrDiv);
		compDiv.appendChild(nameDiv);
		compDiv.appendChild(workNumDiv);
		
		compNameDiv.innerHTML = company.cp_company;

		if (company.cp_homepage != '') {
			var site = 'http://' + company.cp_homepage.replace(/^[\w\W\d]*http:\/\/|www./gi,'');
			compNameDiv.style.cursor = 'pointer';
			compNameDiv.title = 'Visit ' + company.cp_company + '\'s homepage';
			
			Event.observe(compNameDiv, 'mouseenter', function () {
				this.style.textDecoration = 'underline';
			});
			Event.observe(compNameDiv, 'mouseleave', function () {
				this.style.textDecoration = '';
			});
			
			Event.observe(compNameDiv, 'click', function () {
				var newWin = window.open(this.site);
				newWin.focus();
			}.bind({site : site}));
		}
		
		if (listing.mailcity != '') {
			addrDiv.innerHTML = listing.mailcity.replace(/[.]$/g, '');
		}
		else if (listing.city != '') {
			addrDiv.innerHTML = listing.city.replace(/[.]$/g, '');
		}
		
		if (listing.state != '') {
			addrDiv.innerHTML += ', ' + listing.state;
		}
		
		if (listing.zip != '') {
			addrDiv.innerHTML += ', ' + listing.zip;
		}
		
		nameDiv.innerHTML = agent.firstname+' '+agent.lastname;
		
		if (agent.homepage != '') {
			var site = 'http://' + agent.homepage.replace(/^[\w\W\d]*http:\/\/|www./gi,'');
			nameDiv.style.cursor = 'pointer';
			nameDiv.title = 'Visit ' + agent.firstname + ' ' + agent.lastname + '\'s homepage';

			Event.observe(nameDiv, 'mouseenter', function () {
				this.style.textDecoration = 'underline';
				
			});
			Event.observe(nameDiv, 'mouseleave', function () {
				this.style.textDecoration = '';
			});
			
			Event.observe(nameDiv, 'click', function () {
				var newWin = window.open(this.site);
				newWin.focus();
			}.bind({site : site}));
		}
		
		addressDiv.innerHTML = listing.streetnum+' '+listing.streetdir+' '+listing.streetname;
		
		workNumDiv.innerHTML = ' / ' + (agent.workphone || company.cp_workphone || '...');
	} 
	else {
		
		/*  mailto popup box */
		 if (idx.agentid) {
			moreInfo.mailto = {
				classid: listing.classid
				,address: listing.streetnum +' ' + listing.streetdir + ' ' + listing.streetname
				,agentname: idx.name
				,agentid: idx.agentid
			}
		} else {
			moreInfo.mailto = {
				classid: listing.classid
				,address: listing.streetnum +' ' + listing.streetdir + ' ' + listing.streetname
				,agentname: agent.firstname + ' ' + agent.lastname
				,agentid: agent.agentuserid
			}
		}
		
		Event.observe(moreInfo, 'click', function () {
			mailto(this.mailto.classid, this.mailto.address, this.mailto.agentname, this.mailto.agentid);
		});
		
		compDiv.style.height = '42px';
		compDiv.style.lineHeight = '100%';
		
		var idxImgDiv = document.createElement('div');
		idxImgDiv.style.cssFloat = 'left';idxImgDiv.style.styleFloat = 'left';
		idxImgDiv.style.margin = '1px 0px 0px 2px';
		
		var idxBodyDiv = document.createElement('div');
		idxBodyDiv.style.cssFloat = 'left';idxBodyDiv.style.styleFloat = 'left';
		idxBodyDiv.style.margin = '2px 0px 0px 5px';
		
		var nameDiv = document.createElement('div');
		nameDiv.className = 'compName';
		nameDiv.style.cssFloat = 'left';nameDiv.style.styleFloat = 'left';
		nameDiv.style.fontWeight = 'bold';
		
		var addrDiv = document.createElement('div');
		addrDiv.style.cssFloat = 'left';addrDiv.style.styleFloat = 'left';
		addrDiv.style.width = '200px';
		addrDiv.style.height = '5px';
		addrDiv.style.fontWeight = 'bold';
					
		var addressDiv = document.createElement('div');
		addressDiv.style.cssFloat = 'left';addressDiv.style.styleFloat = 'left';
		addressDiv.style.width = '200px';
		addressDiv.style.marginTop = '0px';
		
		var workNumDiv = document.createElement('div');
		workNumDiv.style.cssFloat = 'left';workNumDiv.style.styleFloat = 'left';
		workNumDiv.style.marginTop = '0px';
		
		var cityDiv = document.createElement('div');
		cityDiv.style.cssFloat = 'left';cityDiv.style.styleFloat = 'left';
		cityDiv.style.width = '200px';
		cityDiv.style.marginTop = '3px';
		
		var legalDiv = document.createElement('div');
		legalDiv.className = 'idxlegal';
		legalDiv.style.cssFloat = 'left';legalDiv.style.styleFloat = 'left';
		
		var clrB1 = document.createElement('br');
		clrB1.style.clear = 'both';
		var clrB2 = document.createElement('br');
		clrB2.style.clear = 'both';
		var clrB3 = document.createElement('br');
		clrB3.style.clear = 'both';
		
		compDiv.appendChild(idxImgDiv);
		idxBodyDiv.appendChild(addrDiv);
		idxBodyDiv.appendChild(nameDiv);
		idxBodyDiv.appendChild(clrB2);
		idxBodyDiv.appendChild(addressDiv);
		idxBodyDiv.appendChild(workNumDiv);
		idxBodyDiv.appendChild(clrB3);
		idxBodyDiv.appendChild(cityDiv);
		idxBodyDiv.appendChild(legalDiv);
		compDiv.appendChild(idxBodyDiv);
						
		var idxImg = new Image(40,40);
		idxImg.src = 'http://irasuite.com/wwwroot/remaint/mapsearch/images/idxsmall.jpg';
		idxImgDiv.appendChild(idxImg);
	
		addrDiv.innerHTML = '&nbsp;';
		
		var name = document.createElement('span');
		name.innerHTML = idx.name;
		name.className = 'compName';
		name.style.cursor = 'pointer';
		name.title = 'Visit ' + idx.name + '\'s homepage';
		Event.observe(name, 'click', function () {
			var homepage  = idx.homepage;
			homepage  = 'http://' + homepage.replace(/http:\/\/|www./g,'');
			var newWindow = window.open(homepage);
			newWindow.focus();
		});
		
		nameDiv.appendChild(name);
		
		var address = document.createElement('span');
		address.innerHTML = listing.streetnum+' '+listing.streetdir+' '+listing.streetname+'<br />';
		
		var city = document.createElement('span');
		if (listing.mailcity != '' && listing.mailcity != listing.city) {
			city.innerHTML = listing.mailcity+' / '+listing.city;
		} 
		else if (listing.mailcity != '') {
			city.innerHTML = listing.mailcity;
		}
		else if (listing.city != '') {
			city.innerHTML = listing.city;
		}
		addressDiv.appendChild(address);
		cityDiv.appendChild(city);
		
		var workNum = document.createElement('span');
		workNum.innerHTML = idx.phone;
		workNumDiv.appendChild(workNum);
		
		legalDiv.innerHTML = 'Listed by '+company.cp_company+', '+company.cp_address1;
	}
	containerDiv.classid = listing.classid
	
	return containerDiv;
}

iraSuite.createInfoLnk = function (listing, text, idx) {
	
	var lnk = document.createElement('span');
	lnk.className = 'fLink';
	
	if (typeof text === 'string') {
		lnk.innerHTML = text;
	} else {
		lnk.appendChild(text);	
	}

	if (idx) {
		Event.observe(lnk, 'click', function () {
			var newWin = window.open('/templates/reales/re_dishomes.cfm?classid=' + listing.classid + '&board_id=' + idx.boardid + '&header=' + idx.header + '&css=default.css&header_pg=' + idx.header + '&idxcomp_id=' + idx.compid);
			newWin.focus();
		});
	} else {
		Event.observe(lnk, 'click', function () {
			var newWin = window.open('/templates/reales/re_dishomes.cfm?classid='+listing.classid);
			newWin.focus();
		});	
	}
	return lnk;
}

iraSuite.requestPropertyInfo = function(optObj){
		var optObj = optObj || {};
		//Email Required
		if(!optObj.email) {
			alert("mailtoForm must be passed an email");
		}
		//if sent a subject then text, if not inputbox
		if(!optObj.subject){
			var subject = '<tr><tr><td align="right" style="color: red; font-weight: bold; vertical-align: top;">*</td><td>Subject:</td><td align="right"><input id="subj" size="37" maxlength="50"></td></tr>';	
		} 
		else {
			var subject ='<tr><td></td><td>Subject:</td><td id="subj"><b>'+optObj.subject+'</b></td></tr>';
		}
		//if show email is false email will be kept private
		var showEmail = '<center><tr><td></td><td colspan="2" align="right"><font size="3pt">To:&nbsp;&nbsp;</td><td id="mailTo"><b>'+optObj.email+'</b></font></td></tr></center><br><br>';
		if(optObj.showEmail){
			if(optObj.showEmail == 'false') showEmail = '';
		}
		if (!window.iraSuite.requestPropertyInfoBox){
			if(!optObj.innerHTML) {
				var iHTML = ['<div style="text-align:center>'];
				iHTML.push(showEmail);
				iHTML.push('<table style="font-family: Verdana,Arial; font-size: 11px; vertical-align: top;" cellspacing="0">');
				iHTML.push('<tr><td align="right" style="color: red; font-weight: bold;">*</td><td>Your Name:</td><td align="right"><input id="replyName" size="37" maxlength="50"></td></tr>');
				iHTML.push('<tr><td align="right" style="color: red; font-weight: bold;">*</td><td>Your Email:</td><td align="right"><input id="replyEmail" size="37" maxlength="50"></td></tr>');
				iHTML.push('<tr><td align="right" style="color: red; font-weight: bold;">*</td><td>Confirm Email:</td><td align="right"><input id="confirmReplyEmail" size="37" maxlength="50"></td></tr>');
				iHTML.push('<tr><td></td><td>Your Phone:</td><td align="right"><input id="replyPhone" size="37" maxlength="30"></td></tr>');
				iHTML.push('<tr><td>&nbsp;</td></tr>'+subject);
				iHTML.push('<tr><td align="right" style="color: red; font-weight: bold; vertical-align: top;">*</td><td colspan="2"><textarea rows="5" cols="40" id="msg"></textarea></td></tr></table><br>');
				iHTML.push('<div style="font-size: 10px; padding-bottom: 12px; text-align: center; font-style: italic;">Items marked with <span align="right" style="color: red; font-weight: bold;">*</span> are Required</div></div>');
	
				optObj.innerHTML = iHTML.join('');
			}	
			iraSuite.requestPropertyInfoBox = createForm(optObj);	
			iraSuite.requestPropertyInfoBox.setTitle(optObj.title || 'Send Message');
			iraSuite.requestPropertyInfoBox.button.innerHTML = optObj.buttontext || 'Send';
	
			if(optObj.width) iraSuite.requestPropertyInfoBox.style.width = optObj.width;
			if(optObj.titleStyle) iraSuite.requestPropertyInfoBox.setTitle(optObj.title || 'Send Message',optObj.titleStyle);
	
			iraSuite.requestPropertyInfoBox.onEnterKey = function() {
				if($('requestFormNameInput').value == ''){
					alert("Please Enter Your Name");
					return;
				}
				else if($('requestFormEmailInput').value == ''){
					alert("Please Enter An Email Address");
					return;
				}
				else if(!testEmails($('requestFormEmailInput').value)){
					alert("Email Addresses Do Not Match");
					return;
				}
				else if($('requestFormEmailInput').value != $('requestFormEmailConfirmInput').value){
					alert("Email Addresses Do Not Match");
					return;
				}
				else if($('requestFormMessage').value == ''){
					alert("Please Enter A Message");
					return;
				}
				else if($('requestFormHaveAgent').checked && $('requestFormHaveAgentName').value == ''){
					alert("Please Enter The Name Of The Agent You Are Working With");
					return;
				}
				new Ajax.Request('/wwwroot/remaint/ajax/requestmoreinfoemail.cfm', {
					method:'post'
					,parameters: {classid:optObj.classid, user_id:optObj.agentId, email:optObj.email, search:optObj.search, pathName:optObj.pathName, did:optObj.did, phone:$('requestFormPhoneInput').value, msg:$('requestFormMessage').value, name:$('requestFormNameInput').value, bestTime:$('requestFormBestTime').value, haveAgent:$('requestFormHaveAgent').checked, myAgent:$('requestFormHaveAgentName').value}
					,onSuccess: function(){alert('Message Has Been Sent!');iraSuite.requestPropertyInfoBox.close();}
				});
			};
			
		}
		(optObj.position && optObj.postiton != 'center') ? iraSuite.requestPropertyInfoBox.show().position(optObj.position) : iraSuite.requestPropertyInfoBox.show().center();
		return iraSuite.requestPropertyInfoBox;
}
