//CSSRule ('.searchDiv',{position:'absolute',border:'1px solid black',backgroundColor:'white',padding:'8px',visibility:'hidden'})
document.write('<script src="/wwwroot/t/tricityidx/counties.js"></script>');
document.write('<script src="/wwwroot/t/tricityidx/cities.js"></script>');
document.write('<script src="/wwwroot/t/tricityidx/boards.js"></script>');

CSSRule ('.idxChkBx',{cursor:'pointer'});

CSSRule ('.idxCitiesDiv',{border:'1px solid #6d90b0',backgroundColor:'#edf5fb'},{insertOnly:true})
CSSRule ('.idxCitiesDiv',{visibility:'hidden',position:'absolute',overflow:'hidden',zIndex:'9999'})

CSSRule ('.cImage',{cursor:'pointer'});

CSSRule ('#searchForm td',{textAlign:'left'});
CSSRule ('#searchForm .ar',{textAlign:'right'});
CSSRule ('.idxCitiesHdr',{backgroundColor:'#d5ebff',borderBottom:'1px solid #6d90b0',height:'33px',padding:'0px 8px',cursor:'pointer'},{insertOnly:true})
CSSRule ('.idxBut',{margin:'6px 12px 6px 0px',float:'right'},{insertOnly:true})
CSSRule ('.idxCitiesTable',{fontSize:'11px',padding:'0px'},{insertOnly:true})
CSSRule ('.idxCitiesTable div',{height:'20px',overflow:'hidden',whiteSpace:'nowrap'},{insertOnly:true})
CSSRule ('.idxSel',{backgroundColor:'blue',color:'white'},{insertOnly:true})
CSSRule ('.idxPTypeSel',{backgroundColor:'green',color:'white'},{insertOnly:true})
//CSSRule ('.idxCounty',{fontWeight:'bold',fontSize:'12px',paddingLeft:'8px',paddingTop:'4px',cursor:'pointer'})
CSSRule ('.idxCounty',{fontWeight:'bold',fontSize:'12px',cursor:'pointer'},{insertOnly:true})


CSSRule ('.fLink',{fontSize:'12px',cursor:'pointer',textDecoration:'underline',color:'blue'},{insertOnly:true})
CSSRule ('.totalRecs',{paddingLeft:'4px',paddingRight:'4px'})
CSSRule ('.startRow',{paddingLeft:'4px',paddingRight:'4px'})
CSSRule ('.endRow',{paddingLeft:'4px',paddingRight:'4px'})

CSSRule ('#controlDiv',{position:'relative',textAlign:'left',display:'none',fontSize:'14px',display:'none',height:'20px'})
CSSRule ('#resultsDiv',{display:'none',paddingTop:'18px'})
CSSRule ('#resultsFooter',{display:'none',paddingTop:'18px'})
//CSSRule ('.favsEmailDiv',{display:'none',padding:'6px 6px 6px 20px',fontSize:'12px'})
CSSRule ('.favsPrompt',{visibility:'hidden',position:'absolute',border:'1px solid black',backgroundColor:'white',padding:'9px', width:'500px',fontSize:'12px'})
CSSRule ('.favsMenu',{visibility:'hidden',position:'absolute',border:'1px solid black',backgroundColor:'white',padding:'6px',fontSize:'12px'})
CSSRule ('.favsMenu div',{padding:'3px',cursor:'pointer'})
CSSRule ('.favsP',{cursor:'pointer',padding:'8px'})
CSSRule ('.favsB',{fontWeight:'bold'})
CSSRule ('.favsC',{paddingLeft:'20px'})
CSSRule ('.imageDiv',{position:'absolute',border:'3px solid black',zIndex:'5',visibility:'hidden'})


function triCitySearch(elm,optObj){
	//don't show "Get More Information" link if the compid is 0 (as there are no emails in the database)
	if (optObj.comp_ids[0] == 0) {
		CSSRule('.popupEmail',{display:'none'});
		CSSRule('.company',{fontSize:'10px !important', color:'#777 !important'});
	}
	Event.observe(window,'unload',function(){
		if(!this.favs.store)
			return;

		if (this.favs.props && this.favs.store != 'session'){
			var a=[];
			for (var i in this.favs.props)
				if (this.favs.props.hasOwnProperty(i))
					a.push(i);
			this.favs.props = a;
		}

		if (this.favs.store == 'session'){
			eraseCookie('favs')
			return;
		}
		else if (this.favs.store == 'server'){
			new Ajax.Request('/wwwroot/t/tricityidx/idxFavs.cfm?',{
				parameters:{
					email:this.favs.email,
					propids:this.favs.props.join(','),
					notify:this.favs.notify,
					action:'save',
					comp_id: this.comp_ids[0]
				},
				onException:function(o,e){
					//alert('1:exception')
				}
			})
		}
		createCookie('favs',Object.toJSON(this.favs),180)
	}.bind(this))
	
	this.divRegistry = [];
	this.selectedCities=[];
	this.images = [];

	if (!optObj)
		optObj = {};
	
	// Custom event on "Search" button press
	this.searchEvent = optObj.searchEvent || false;
	this.onLoading = optObj.onLoading || false;
	this.onLoad = optObj.onLoad || false;
	this.onError = optObj.onError || '';
	// Variables
	this.boardids = optObj.boardids || ['ira','mid','sag','bay'];
	this.comp_ids = optObj.comp_ids || [];

	this.formFormat = optObj.formFormat || 0;
	this.waterfrontonly = optObj.waterfrontonly || 0;
	
	new Ajax.Request('/wwwroot/t/tricityidx/getcities.cfm?',{parameters:{boardids:this.boardids,comp_id:this.comp_ids[0]}})
	//setTimeout(function(){
	//	for (var i in vCounties)
	//		if (vCounties.hasOwnProperty(i))
	//			alert(iraCountiesX[i].COUNTY)
		//alert(vCounties.length)
	//},1000)
	
	this.elm = $(elm);

	var a, x;
	
	if (window.innerHeight){
		this.windowWidth = window.innerWidth;
		this.windowHeight = window.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight){
		this.windowWidth = document.documentElement.clientWidth;
		this.windowHeight = document.documentElement.clientHeight;
	}
	else if (document.body){
		this.windowWidth = document.body.clientWidth;
		this.windowHeight = document.body.clientHeight;
	}
	
	a=[];
	a.push('<div id="controlDiv" ><div class="fLink" style="float:left">Modify Your Search</div><div class="fLink" style="float:left;padding-left:12px">Favorites</div>');
	a.push('<div style="float:right"><span class="totalRecs"></span>Matching Records.<span class="startRow"></span>through')
	a.push('<span class="endRow"></span>displayed.<br>Click <img src="/wwwroot/t/tricityidx/images/star_off.gif"> to add property to your favorites.</div></div>')
	a.push('<div id="resultsDiv"></div>')
	
	a.push('<div id="resultsFooter"><span class="fLink footer_prev" style="margin-right:8px">Previous</span><span class="fLink footer_next" style="margin-left:8px">Next</span></div>')
	
	a.push('<div id="searchDiv">')
	if (optObj.title)
		a.push(optObj.title);
	else
		a.push('<h2>Tri-County Property Search</h2>')
	
	// Temp fix for search form formats
	if (this.formFormat == 1) {
		a.push('<form name="searchForm" id="searchForm" onsubmit="return false"><table class="searchTable" border="0" cellspacing="1" cellpadding="1">')
		a.push('<tr><td class="ar">Price:</td><td colspan="3"><input digits="11" type="text" size="11" name="fPrice">')
		a.push(' to <input digits="11" type="text" size="11" name="tPrice"></td></tr>');
		
		//a.push('<tr><td class="ar">Sq Feet:</td><td colspan="3"><input digits="8" type="text" size="11" name="fSqFeet">')
		//a.push(' to <input digits="8" type="text" size="11" name="tSqFeet"></td></tr>');
		
		
		a.push('<tr><td class="ar">Property Types:</td><td class="idxChkBx pType"><input  name="propTypes"  value="Single" type="checkbox">Single Family</td>')
		
		a.push('</tr><tr><td></td><td class="idxChkBx pType"><input type="checkbox" name="propTypes" value="Vacant">Vacant Land</td>')
		
		a.push('<td></td><td class="idxChkBx pType"><input type="checkbox" name="propTypes" value="Condo">Condo</td></tr>')
		
		a.push('<tr><td class="ar">Counties:</td><td colspan="3"><input id="idxCounties" type="text" style="width:200px"></td></tr>')
		a.push('<tr><td class="ar">Cities/Townships:</td><td colspan="3"><input id="idxCities" type="text" style="width:200px"></td></tr>')
	} else {
		a.push('<form name="searchForm" id="searchForm" onsubmit="return false"><table>')
		a.push('<tr><td class="ar">Price:</td><td colspan="3" class="ar"><input digits="11" type="text" size="20" name="fPrice">')
		a.push(' to <input digits="11" type="text" size="20" name="tPrice"></td></tr>');
		
		a.push('<tr><td class="ar">Sq Feet:</td><td colspan="3" class="ar"><input digits="8" type="text" size="20" name="fSqFeet">')
		a.push(' to <input digits="8" type="text" size="20" name="tSqFeet"></td></tr>');
		
		a.push('<tr><td class="ar">Bedrooms:</td><td colspan="3" class="ar"><input digits="1" type="text" size="20" name="fBeds">')
		a.push(' to <input digits="1" type="text" size="20" name="tBeds"></td></tr>');
		
		a.push('<tr><td class="ar">Bathrooms:</td><td colspan="3" class="ar"><input digits="1" decimal="1" type="text" size="20" name="fBaths">')
		a.push(' to <input digits="1" decimal="1" type="text" size="20" name="tBaths"></td></tr>');
	
		a.push('<tr><td class="ar">Street Name:</td><td colspan="3" class="ar"><input type="text" size="30" name="streetName"></td></tr>');
		
		a.push('<tr style="height:15px"><td>&nbsp;</td></tr><tr><td class="ar">Property Types:</td><td class="idxChkBx pType"><input  name="propTypes"  value="Single" type="checkbox">Single Family</td>')
		a.push('<td></td><td class="idxChkBx pType"><input type="checkbox" name="propTypes" value="Multi">Multi Family</td></tr>')
		
		a.push('</tr><tr><td></td><td class="idxChkBx pType"><input type="checkbox" name="propTypes" value="Vacant">Vacant Land</td>')
		a.push('<td></td><td class="idxChkBx pType"><input type="checkbox" name="propTypes" value="Waterfront">Waterfront</td></tr>')
		
		a.push('</tr><tr><td></td><td class="idxChkBx pType"><input type="checkbox" name="propTypes" value="Commercial">Commercial</td>')
		a.push('<td></td><td class="idxChkBx pType"><input type="checkbox" name="propTypes" value="Condo">Condo</td></tr>')
		
		a.push('<tr><td class="ar">Counties:</td><td colspan="3"><input id="idxCounties" type="text" style="width:340px"></td></tr>')
		a.push('<tr><td class="ar">Cities/Townships:</td><td colspan="3"><input id="idxCities" type="text" style="width:340px"></td></tr>')
	}
	if (idxFormats.length > 1){
		a.push('<tr><td align="right">Output Format:</td><td colspan="3"><select id="outputFormat">')
		for (var i=0;i<idxFormats.length;i++)
			a.push('<option value="'+i+'">'+idxFormats[i].name)
		}
	else
		a.push('<input type="hidden" id="outputFormat" value="0">')
		
	a.push('</select></td></tr>')
	
	if (this.formFormat == 1) {
		a.push('<tr><td colspan="4" align="right"><img src="/wwwroot/t/tricityidx/formats/images/michiganwaterfront_search.png" style="float:right;margin-right:12px;cursor:pointer;padding-top:5px;" class="searchButton"><span style="display:none"><button id="viewFavorites" disabled="true">View Your Favorites</button></span></td></tr>')
	} else {
		a.push('<tr><td colspan="4"><button class="searchButton">Search</button><button id="viewFavorites" disabled="true">View Your Favorites</button></td></tr>')
	}
	
	a.push('<tr><td></td><td colspan="4"><div style="width:25px;height:25px;overflow:hidden"><span id="testSpan" style="visibility:hidden;border:1px solid white;font-size:12px;white-space:nowrap"></span></div></td></tr>')
	
	a.push('</table>')
	a.push('<img id="idxCiImg" src="/wwwroot/t/tricityidx/images/search_select_button.gif" style="position:absolute;display:block;padding:0px">')
	a.push('<img id="idxCoImg" src="/wwwroot/t/tricityidx/images/search_select_button.gif" style="position:absolute;display:block;padding:0px"></form></div>')
	this.elm.innerHTML = a.join('');

	
	this.searchForm = $('searchForm');
	this.searchDiv = $('searchDiv');
	this.resultsDiv = $('resultsDiv');
	this.controlDiv = $('controlDiv');
	this.resultsFooter = $('resultsFooter');
	this.iCities = $('idxCities');
	this.iCounties = $('idxCounties');
	this.ciImg = $('idxCiImg');
	this.coImg = $('idxCoImg');
	this.testSpan = $('testSpan');
	this.controlObj = {start:0};
	this.controlObj.step = optObj.listingsPerPage || 10;

	var favs = readCookie('favs');
	if (favs)
		eval("this.favs="+favs)
	else
		this.favs = {props:[],store:null,email:''}
		

	if (this.favs.props.length){
		new Ajax.Request('/wwwroot/t/tricityidx/ajax/getProperties.cfm',
			{	parameters:{propids:this.favs.props.join(',')},
				onComplete:function(){
					this.favs.props=[];
					for (var i=0;i<idxProperties.length;i++)
						this.favs.props[idxProperties[i].PROPID] = idxProperties[i];
					this.controlObj.favs = this.favs.props;
					$('viewFavorites').disabled = !this.favs.props.length;
					this.loadImages();
				}.bind(this),
				onException:function(requestor,eObj){
					//alert('2:exception');
					//alert(eObj.message);
				}
			})
	}


	this.controlObj.favs = this.favs.props;
	this.controlObj.images = this.images;
	
	this.favsPrompt = $(document.createElement('div'));
	this.favsPrompt.className = 'favsPrompt';
	var a = [];
	
	var c = s = n = '';
	var d = 'display:none';
	
	if (this.favs.store == 'session') {
		c = ' checked ';
		s = ' style="background-color:lightblue" ';
	}
	a.push('<div style="font-size:16px;font-weight:bold;text-align:center;margin-bottom:8px">Where do you want to save your favorites?</div>');
	a.push('<form onsubmit="return false" name="fFavs" id="fFavs" style="margin:0px"><div class="c"><div class="favsP" '+s+'><div class="favsB"><input type="radio" name="favChoice" value="session"');
	a.push(c+'>Session</div>');
	a.push('<div class="favsC">Your favorites will be discarded when you leave this search screen.</div></div>');
	c = s = '';
	if (!this.favs.store || this.favs.store == 'cookies'){
		c = ' checked ';
		s = ' style="background-color:lightblue" ';
	}
	a.push('<div class="favsP"'+s+'><div class="favsB"><input type="radio" name="favChoice" value="cookies"');
	a.push(c+'>Cookies</div>');
	a.push('<div class="favsC">Your favorites will be saved for you to access later but will only be available from the computer that you are now using.</div></div>');
	c = s = '';
	if (this.favs.store == 'server'){
		c = ' checked ';
		s = ' style="background-color:lightblue" ';
		d = ''
	}
	if (this.favs.notify)
		n = 'checked'
	a.push('<div class="favsP"'+s+'><div class="favsB"><input type="radio" name="favChoice" value="server"');
	a.push(c+'>Server</div>');
	a.push('<div class="favsC"><input type="checkbox" class="favsNotify" '+n+' style="margin-left:-4px"><span style="font-weight:bold" onclick="this.previousSibling.click()">Notify me of price changes to my favorites.</span><br>Your favorites will be saved for you to access later from any computer.</div>');
	a.push('<div class="favsC favsEmailDiv" style="'+d+';margin-top:4px">Enter your email:<br>');
	a.push('<input name="favsEmail" id="favsEmail" value="'+this.favs.email+'" type="text" size="30" maxlength="30"><br>');
	a.push('Your Email is needed for you to retrieve your favorites later from another computer. It will never be shared or sold to anyone!</div>');
	a.push('</div>');
	a.push('<div class="b" style="text-align:right"><button>Continue</button></div></form>')
	a.push('<div style="text-align:center;font-size:11px">To change this option in the future, click favorites, then options</div>')
	this.favsPrompt.innerHTML = a.join('');
	document.body.appendChild(this.favsPrompt);


	
	this.processFavsOpts = function(){
		var favChoice = this.getRadioValue($('fFavs').favChoice);
		if (favChoice == 'server'){
			var email = $('favsEmail').value
			if (!testEmail(email)){
				alert('A valid email is needed to save your favorites on the server.\nPlease enter a valid email address or change your save option.')
				return;
			}
			this.favs.email = email;
		}
		if (favChoice){
			this.favs.store = favChoice;
			popForm('destroy')
		}
		this.favs.notify = this.favsPrompt.getElementsByClassName('favsNotify')[0].checked
	}.bind(this)
	
	Event.observe(this.favsPrompt,'keypress',function(e){
		if (e.keyCode == 13)
			this.processFavsOpts();
	}.bind(this))
	
	Event.observe(this.favsPrompt,'click',function(e){
		var t = $(e.target) || $(e.srcElement);

		if(t.tagName == 'BUTTON'){
			this.processFavsOpts();
			return;
		}

		while (t.className != 'favsP' && t != this.favsPrompt)
			t = t.parentNode;
		if (t.className != 'favsP')
			return;
			
		t.firstChild.firstChild.checked = true;
		
		var divs=this.favsPrompt.getElementsByClassName('favsP')
		for (var i=0;i<divs.length;i++)
			divs[i].style.backgroundColor = ''			
			
		t.style.backgroundColor = 'lightblue'
		
		if (t.firstChild.firstChild.value == 'server')
			this.favsPrompt.getElementsByClassName('favsEmailDiv')[0].style.display='block'
		else {
			this.favsPrompt.getElementsByClassName('favsEmailDiv')[0].style.display='none'
			this.favsPrompt.getElementsByClassName('favsNotify')[0].checked = false;
		}

	}.bindAsEventListener(this))

	
	
	


	this.getRadioValue = function(radios){
		for (var i=0;i<radios.length;i++)
			if (radios[i].checked)
				return radios[i].value;
	}
	
	/*this.changeClass = function(elm, oldClass, newClass){
		while (elm && !elm.hasClassName(oldClass))
			elm = $(elm.parentNode)
		if(elm){
			elm.addClassName(newClass)
			elm.removeClassName(oldClass)
		}
	}*/
		
	// click on a star. or brochure link
	Event.observe(this.resultsDiv,'click',function(e){
		var t = $(e.target) || $(e.srcElement);
		var elm = t;
		while (elm && elm.hasClassName && !elm.hasClassName('idxProperty'))
			elm = $(elm.parentNode)
		
		if (!elm.getAttribute)
			return;
		
		var i = elm.getAttribute('i');
		
		if (t.hasClassName('cImage')){
			//alert(this.controlObj.dataArray[i].PROPID)
			//alert(this.controlObj.dataArray[i].BOARDID)
			var p = this.controlObj.dataArray[i];
			this.fullImage(p.PROPID,p.BOARDID)
		}
		if (t.hasClassName('star')){
			if (!this.favs.store){
				this.favsOptions()
			}

			if (elm.hasClassName('idxFav')){
				elm.removeClassName('idxFav')
				t.src = t.src.replace(/star_on/,'star_off')
				delete this.favs.props[this.controlObj.dataArray[i].PROPID]
			}
			else{
				this.favs.props[this.controlObj.dataArray[i].PROPID] = this.controlObj.dataArray[i]
				elm.addClassName('idxFav')
				t.src = t.src.replace(/star_off/,'star_on')
			}
		}
		else if (t.hasClassName('brochure')){
			idxBrochures[this.controlObj.dataArray[i].BOARDID].brochure(this.controlObj.dataArray[i],this);
		}
		if (t.hasClassName('popupEmail')){
			if (!companyInfo) var companyInfo = {};
			var sendToName = companyInfo.name || this.controlObj.dataArray[i].LISTINGCOMPANYNAME;
			mailto({
				propid 			: this.controlObj.dataArray[i].PROPID
				,boardid		: this.controlObj.dataArray[i].BOARDID
				,idxcomp_id 	: this.comp_ids[0]
				,sendTo			: sendToName
				,subject		: this.formatAddr(this.controlObj.dataArray[i])
			})
		}
	}.bindAsEventListener(this))

	this.formatAddr = function(obj){
		var a = [obj.STREETNUM
			,obj.STREETDIR
			,obj.STREETNAME+','
			,iraCitiesX[obj.CITY_ID].CITY
			,'#'+obj.BOARDID+obj.MLS]
			if (!obj.STREETNAME)
				a[2] = '';
		return a.join(' ');
	}
	
	this.favsOptions = function(){
		if (this.favsMenu)
			this.favsMenu.style.visibility='hidden';
		pushForm(this.favsPrompt)
		this.favsPrompt.focus()
	}

	Event.observe(this.resultsFooter.lastChild,'click',function(){
		//this.controlObj.start = 155;
		this.controlObj.start += this.controlObj.step;
		this.displayProperties();
	}.bind(this))
	
	Event.observe(this.resultsFooter.firstChild,'click',function(){
		this.controlObj.start -= this.controlObj.step;
		this.displayProperties();
		//Why was this here, on a pure AJAX site? history.go(-1)
	}.bind(this))
	
	
	this.noMatches = function(){
		if (!this.noMatchesDiv){
			var d
			var a = [];
			d = this.noMatchesDiv = $(document.createElement('div'))
			d.className = 'idxCitiesDiv';
			d.style.width='480px';
			a=['<div class="idxCitiesHdr" style="padding:8px;font-size:18px"><div style="float:left">Sorry...</div><img src="/wwwroot/t/tricityidx/images/close_small.gif" style="float:right;margin-top:5px"></div>'	
			,'<div style="padding:8px">No properties were found matching your search options.<p>'
			,'If you would like our help, call us at: <span class="companyphone" style="font-weight:bold"> 800-367-1905</span><br> '
			,'or <span class="fLink" style="font-size:16px;font-weight:bold">click here</span> to tell us what you\'re looking for.<p> Our full time Real Estate Agents have access to all listings for '
			,'Bay, Saginaw, Midland and Arenac Counties.<p> '
			,'Or, you may widen your search options and search again.<p>'
			,'<div style="text-align:center"><button onclick="popForm(\'destroy\');'+this.onError+'">OK</button></div></div>']
			
			
			this.noMatchesDiv.innerHTML = a.join('');
			//tthis.noMatchesDiv.onblur = popForm; 
			this.noMatchesDiv.onkeydown = popForm;
			document.body.appendChild(this.noMatchesDiv)
		}
		this.noMatchesDiv.style.visibility = 'visible';
		pushForm(this.noMatchesDiv,{opacity:.25})
		this.noMatchesDiv.focus();
			
	}
	this.search = function(){
		var parms;
		var msg = [];
		if (!this.saveParms)
			 this.saveParms = {} ;
		
		
		if (this.searchForm.fPrice) {
			if (this.searchForm.fPrice.value && this.searchForm.tPrice.value && parseInt(this.searchForm.fPrice.value) > parseInt(this.searchForm.tPrice.value)) {
				msg.push('Invalid Price Range');
			}
		}
		if (this.searchForm.fSqFeet) {
			if (this.searchForm.fSqFeet.value  &&  this.searchForm.tSqFeet.value && parseInt(this.searchForm.fSqFeet.value) > parseInt(this.searchForm.tSqFeet.value)) {
				msg.push('Invalid Square Feet Range');
			}
		}
		if (this.searchForm.fBeds) {
			if (this.searchForm.fBeds.value && this.searchForm.tBeds.value && parseInt(this.searchForm.fBeds.value) > parseInt(this.searchForm.tBeds.value)) {
				msg.push('Invalid Bedroom Range');
			}
		}
		
		/*if (this.searchForm.fBaths && this.searchForm.tBaths && this.searchForm.tBaths.value) {
			if (this.searchForm.fBaths.value && this.searchForm.tBaths.value && parseInt(this.searchForm.fBaths.value) > parseInt(this.searchForm.tBaths.value)) {
				msg.push('Invalid Bathroom Range');
			}
		}*/
	
		if (msg.length){
			alert(msg.join('\n'));
			return;
		}
		
		parms = Form.serialize(this.searchForm, true)
		
		
		if (this.searchForm.fBaths && this.searchForm.fBaths.value > '' || this.searchForm.tBaths && this.searchForm.tBaths.value > '' || this.searchForm.fBeds && this.searchForm.fBeds.value > '' || this.searchForm.tBeds && this.searchForm.tBeds.value > ''){
				var pt = this.searchForm.propTypes;
				for (var i=0;i<pt.length;i++){
					if (pt[i].checked && (pt[i].value == 'Commercial' || pt[i].value == 'Multi' || pt[i].value == 'Vacant') ){
						var myA = ['Warning!\n\n'
								,'Normally Commercial, Multi Family and Vacant Land '
								,'do not have either bedrooms or bathrooms entered in the listing.\n\n'
								,'Combining Bedrooms and or Bathrooms with these property types will likely '
								,'result in your search missing properties that you may want to view.\n\n'
								,'Click OK to proceed with your search or Click Cancel to change your search options.']
						break;
					}
				}
				if (myA && !confirm(myA.join('')))
					return;
		}	
						
		
		for (var x in parms){
			if(!parms[x].join){
				parms[x] = parms[x].replace(/,/g,'')
			}
		}
		
		if (this.waterfrontonly) {
			parms.waterfrontonly = 1;
		} else {
			parms.waterfrontonly = 0;
		}

		
		
		if (!this.selectedCities.length)
			this.selectedCities = [];
		
		
		parms.city_ids = this.selectedCities.join(',');
		parms.county_ids = this.selectedCounties.join(',');
		parms.comp_ids = this.comp_ids.join(',');
		parms.boardids = this.boardids.join(',');
		
		
		if (Object.toJSON(parms) != Object.toJSON(this.saveParms)){
			this.saveParms = parms;
			if (this.onLoading) {
				this.onLoading();	
			}
			new Ajax.Request('/wwwroot/t/tricityidx/ajax/getProperties.cfm',
				{	parameters:parms,
					onComplete:function(transport){
						if (!window.idxProperties){
							eval(transport.responseText);
						}
						this.controlObj.start = 0;
						if (idxProperties.length){
							this.loadImages();
							this.controlObj.dataArray = idxProperties;
							this.displayProperties();
						}
						else {
							this.noMatches();
						}
					}.bind(this),
					onException:function(requestor,eObj){
						//alert('exception');
						//alert(eObj.message)
						//alert(requestor.transport.responseText)
					}
				}
			)
		}
		else if (!idxProperties.length)
			this.noMatches();
		else {
			this.controlObj.dataArray = idxProperties;
			this.controlObj.start = 0;
			this.displayProperties();
		}
	
	}.bind(this)
	// Append custom search event to button, passed by function init
	if (this.searchEvent) {
		Event.observe(this.elm.getElementsByClassName('searchButton')[0],'click',this.searchEvent)
	}
	// Append main search function event to button
	Event.observe(this.elm.getElementsByClassName('searchButton')[0],'click',this.search)

	this.modifyCriteria = function(){
		this.ciImg.setStyle({display:'block',visibility:'visible'});
		this.coImg.setStyle({display:'block',visibility:'visible'});
		this.resultsDiv.style.display = 'none';
		this.controlDiv.style.display = 'none';
		this.resultsFooter.style.display = 'none';
		this.searchDiv.style.display = 'block';
		$('viewFavorites').disabled = !this.hasFavs();
		this.positionArrows();
	}.bind(this);
	overlayArray.reInit = this.modifyCriteria;

	Event.observe(this.controlDiv.firstChild,'click',function(){
		if(optObj) {
			if(optObj.searchUrl){
				window.location = optObj.searchUrl;
			} else {
				pushF(this.modifyCriteria);
			}
		} else {
			pushF(this.modifyCriteria);
		}
	}.bind(this))

	//pushF(this.displayProperties.bind(this,this.controlObj.start+''));

	Event.observe(this.controlDiv.childNodes[1],'click',function(e){
		if (!this.favsMenu){
			this.favsMenu = $(document.createElement('div'))
			this.favsMenu.className = 'favsMenu';
			document.body.appendChild(this.favsMenu);
			var elm = e.srcElement || e.target;
			var top = elm.offsetHeight;
			var left = 12;
			while (elm && elm.tagName != 'HTML'){
				top += elm.offsetTop;
				left += elm.offsetLeft;
				elm= elm.offsetParent;
			}
			this.favsMenu.style.top = top+'px'
			this.favsMenu.style.left = left+'px'
			this.favsMenu.style.fontSize = 12+'px'
			var a=[];
			a.push('<div class="fLink allFavs">View All Favorites</div>');
			a.push('<div class="fLink getFavs">Retrieve My Favorites</div>');
			a.push('<div class="fLink favsOpts">Options</div>');
			this.favsMenu.innerHTML = a.join('');
			
			Event.observe(this.favsMenu.getElementsByClassName('favsOpts')[0],'click',this.favsOptions.bind(this));
			Event.observe(this.favsMenu.getElementsByClassName('allFavs')[0],'click',this.allFavs.bind(this));

			Event.observe(this.favsMenu,'blur',function(){setTimeout(function(){this.favsMenu.style.visibility='hidden'}.bind(this),180);}.bind(this))
			//Event.observe(this.favsMenu,'mouseover',function(e){
			//	var t = e.srcElement || e.target;
				//if(t.className == '')
			//		t.style.color = 'blue'
			//}.bindAsEventListener(this))
		}
		else if (this.favsMenu.style.visibility=='visible'){
			this.favsMenu.style.visibility='hidden'
			Event.stop(e);
			return;
		}

		this.favsMenu.style.visibility='visible';
		this.favsMenu.style.zIndex=999999;

		this.favsMenu.getElementsByClassName('allFavs')[0].disabled = !this.hasFavs();
		this.favsMenu.focus();
		
	}.bindAsEventListener(this))
	
	this.hasFavs = function(){
		var f = this.favs.props;
		var b = false;
		for (var i in f)
			if (f.hasOwnProperty(i)){
				b = true;
				break;
			}
		return b;
	}

	this.allFavs = function(){
		if (!this.hasFavs())
			return;
		//idxProperties = [];
		this.idxFavs = [];
		for (var i in this.favs.props){
			if (this.favs.props.hasOwnProperty(i))
				this.idxFavs.push(this.favs.props[i]);
		}
		this.controlObj.dataArray = this.idxFavs;
		this.controlObj.start = 0;
		//overlayArray.truncate(0);
		this.displayProperties();
		if(this.favsMenu)
			this.favsMenu.style.visibility='hidden';
		//delete this.saveParms;
	}
	Event.observe($('viewFavorites'),'click',this.allFavs.bind(this))
	
	this.noImage = function(a){
		this.images[a] = null
	}
	this.setImage = function(){
		setTimeout(function(){
			var f = $('outputFormat').value
			var r,h,w,f,nW,nH,adj,t;
			
			t = this;
			r = t.width/t.height;
			h = t.height;
			w = t.width;
			t.style.position='absolute';
			if (r > idxFormats[f].ratio){
				t.height = idxFormats[f].imageHeight;
				nW = Math.floor(idxFormats[f].imageHeight * r);
				t.width = nW;
				adj = Math.floor((idxFormats[f].imageWidth - nW)/2);
				t.style.left = adj+'px';
			} else {
				t.width = idxFormats[f].imageWidth;
				nH = idxFormats[f].imageWidth / r;
				t.height = nH;
				adj = (parseInt(idxFormats[f].imageHeight) - parseInt(nH))/2;
				try {
					t.style.top = Math.round(parseInt(adj))+'px';
				} catch(e) {
					t.style.top = '0px';
				}
				t.style.left = '0px';
			}
		}.bind(this),500);
	}
	
	this.fullImage = function(propid,boardid){
		var i = this.images[propid];
		if (!i) return;
		
		var top, left, el, adj, ni, imgDiv, img;
		if (!this.imageDivs){
			this.imageDivs = [];
			for (var x = 0;x<3;x++){
				img = $(document.createElement('img'))
				imgDiv = $(document.createElement('div'))
				imgDiv.className = 'imageDiv'
				imgDiv.appendChild(img);
				document.body.appendChild(imgDiv)
				img.style.height = img.style.width = 'auto';
				
				Event.observe(img,'load',function(dr){
					getScroll();
					var adj;
					if (this.height < 300){
						this.style.height = 300+'px';
					}
						
					if (this.height > windowHeight){
						this.style.height = windowHeight+'px';
					}
					this.parentNode.style.top = scrollTop+((windowHeight-this.parentNode.clientHeight)/2) +'px'
					this.parentNode.style.left = scrollLeft+((windowWidth-this.parentNode.clientWidth)/2) +'px'
					this.parentNode.style.visibility = 'visible';
					this.parentNode.focus();
					setTimeout(function(){dr.push(this.parentNode)}.bind(this),300)
				}.bind(img,this.divRegistry))
				
				this.imageDivs.push(imgDiv)
			}
		}
		imgDiv = this.imageDivs.shift();
		this.imageDivs.push(imgDiv);
		
		img = imgDiv.firstChild;
		img.style.height = img.style.width = 'auto';

		if (i.large > ''){
			img.src=idxBoardsX[boardid].IMAGEPATH+i.large;
		}
		else
			img.src=i.src;

	}

	this.loadImages = function(arg){
		var s,e,image,imagePath;
		var x = idxProperties;
		
		s = (arg) ? this.controlObj.start + this.controlObj.step : this.controlObj.start;
		
		var e = Math.min((s + this.controlObj.step),x.length);
		for (var i=s;i<e;i++){
			if (idxBoardsX[x[i].BOARDID] && this.images[x[i].PROPID] == undefined){
				imagePath = idxBoardsX[x[i].BOARDID].IMAGEPATH;
				image = document.createElement('img');
				image.className = 'cImage';
				image.large = x[i].LARGEIMAGE;
				image.onload = this.setImage.bind(image);
				image.onerror = this.noImage.bind(this,x[i].PROPID);
				//image.onclick = this.fullImage.bind(this,x[i].PROPID,x[i].BOARDID);
				this.images[x[i].PROPID] = image;
				image.src = imagePath+x[i].IMAGE;
			}
		}
	}
	this.displayProperties = function(start,dataArray){
		if (this.onLoad) {
			this.onLoad();
		}
		if (start !== undefined) {
			if (start){
				// if start is passed, then the call has been pushed onto the iframe/history stack
				// the function is being executed from history
				this.controlObj.start = parseInt(start,dataArray);
				this.controlObj.dataArray = dataArray;
			} else {
				// if no start parm, push it onto the history stack. it will come back to us momentarily
				// with our start parm and our array.
				pushF(this.displayProperties.bind(this,this.controlObj.start+'',this.controlObj.dataArray));
				return;
			}
		}
		
		this.controlObj.end = Math.min(this.controlObj.start+this.controlObj.step-1, this.controlObj.dataArray.length-1);
		this.searchDiv.style.display='none';
		this.resultsDiv.style.display='block';
		this.controlDiv.style.display='block';
		this.resultsFooter.style.display='block';
		this.controlDiv.getElementsByClassName('totalRecs')[0].innerHTML =this.controlObj.dataArray.length;
		this.controlDiv.getElementsByClassName('startRow')[0].innerHTML = this.controlObj.start+1;
		this.controlDiv.getElementsByClassName('endRow')[0].innerHTML = this.controlObj.end+1;
		
		idxFormats[$('outputFormat').value].load(this.resultsDiv,this.controlObj)
			
		
		var displayType1 = this.resultsFooter.firstChild.getStyle('display');
		var displayType2 = this.resultsFooter.lastChild.getStyle('display');
				
		this.resultsFooter.firstChild.style.display = (this.controlObj.start) ? 'inline' : 'none'
		this.resultsFooter.lastChild.style.display = (this.controlObj.end < this.controlObj.dataArray.length-1) ? displayType2.toString() : 'none'
		
		
		window.scroll(0,0)
		setTimeout(function(){this.loadImages('pre')}.bind(this),100);
		this.ciImg.setStyle({display:'none',visibility:'hidden',position:'absolute',top:-500+'px'});
		this.coImg.setStyle({display:'none',visibility:'hidden',position:'absolute',top:-500+'px'});
	}	
	
	
	
	this.closeCounties = function(e){
		if (!this.countiesDiv || this.countiesDiv.style.visibility != 'visible')
			return;
		//alert(this.countiesDiv.style.visibility)
		var t = e.srcElement || e.target
		var closeCounties = $('closeCounties');
		
		while (t!=this.countiesDiv && t.tagName != 'HTML' && t!=closeCounties)
			t=t.parentNode;

		if (t==this.countiesDiv)			
			return;

		if (this.selectedCounties.length == 0){
			alert('Please select at least one county before continuing. ')
			return;
		}
		this.countiesDiv.style.visibility='hidden'
		window.scroll(this.countiesDiv.scLeft,this.countiesDiv.scTop)
		var a = [];
		for (var i=0;i<this.selectedCities.length;i++)
			if(this.selectedCounties.indexOf(iraCitiesX[this.selectedCities[i]].COUNTY_ID)>-1)
				a.push(this.selectedCities[i])
		this.citiesText(a);
	}


	Event.observe(document.body,'click',this.closeCounties.bindAsEventListener(this));
	Event.observe(document.body,'click',function(e){
		if (!this.citiesDiv || this.citiesDiv.style.visibility == 'hidden')
			return;

		var t = e.srcElement || e.target
		while (t!=this.citiesDiv && t.tagName != 'HTML' && t != $('closeCities'))
			t=t.parentNode;
		if (t==this.citiesDiv)			
			return;

		this.citiesDiv.style.visibility='hidden';
		window.scroll(this.citiesDiv.scLeft,this.citiesDiv.scTop)
	}.bindAsEventListener(this))

	
	
	
	
	
	this.check = function(event){
		var src = ($(event.srcElement) || $(event.target))
		var par = $(src.parentNode)

		if (src.hasClassName('idxChkBx'))
			src.firstChild.checked = !src.firstChild.checked;
		else if (par.hasClassName('idxChkBx'))
			src = par;
		else
			return;
	
		var county_id;
		if (src.hasClassName('idxCounty')){
			src.county_id = src.firstChild.value;
			var tds = this.citiesDiv.getElementsByTagName('td')
			var b = src.firstChild.checked
			for (var i=0;i<tds.length;i++){
				if($(tds[i].firstChild).hasClassName('idxCounty'))
					county_id = tds[i].firstChild.firstChild.value;
				else
					county_id = iraCitiesX[tds[i].firstChild.firstChild.value].COUNTY_ID;

				if (county_id == src.county_id){
					(b) ? tds[i].firstChild.addClassName('idxSel') : tds[i].firstChild.removeClassName('idxSel')
					tds[i].firstChild.firstChild.checked = b;
				}
			}
			this.citiesText();
			return;
		}

		if (src.firstChild.checked)
			if (src.hasClassName('pType'))
				src.addClassName('idxPTypeSel')
			else 
				src.addClassName('idxSel')
		else
			if (src.hasClassName('pType'))
				src.removeClassName('idxPTypeSel')
			else 
				src.removeClassName('idxSel')

		if (src.firstChild.name == 'city_ids'){
			this.citiesText()
			this.chkCounty([iraCitiesX[src.firstChild.value].COUNTY_ID])
			this.iCities.focus()
			//this.iCities.select()
		}
		else if (src.firstChild.name == 'county_ids') {
			this.iCounties.select()
			this.iCounties.focus()
		}
	}

	
	
	this.bCheck = this.check.bindAsEventListener(this);
	
	
	this.createCountiesDiv = function(){
		this.countiesDiv = $(document.createElement('div'))
		this.countiesDiv.className = 'idxCitiesDiv';
		document.body.appendChild(this.countiesDiv);

		var totalCounties = 0;
		
		var tempCounties = [];
		
		for (var i in vCounties) {
			if (vCounties.hasOwnProperty(i)){
				tempCounties.push(iraCountiesX[i])
			}
		}
		
		tempCounties.sort(function(a,b){
			return (a.COUNTY < b.COUNTY) ? -1 : 1 
		})
		
		a=[];
		a.push('<div class="idxCitiesHdr">');
		a.push('<div style="float:right;margin-top:4px"><button id="closeCounties">Continue</button></div>');
		//a.push('<div class="idxBut" id="closeCounties" style="margin-right:0px">&nbsp;<img src="/wwwroot/t/tricityidx/images/close_small.gif" style="margin-left:0px"></div>');
		//a.push('<img id="unChkAllCounties" class="idxBut" style="margin-right:6px" src="/wwwroot/t/tricityidx/images/uncheckall.gif">');
		//a.push('<img id="chkAllCounties"  class="idxBut" src="/wwwroot/t/tricityidx/images/checkall.gif">');
		a.push('</div><form name="idxCountiesForm" id="idxCountiesForm" style="margin:0px"><table class="idxCitiesTable" cellpadding="0" cellspacing="0">');
		//var cols=7;
		
		var cols=Math.max(Math.min(7,Math.ceil(Math.sqrt(tempCounties.length))-2),1)
		var rows=Math.ceil(tempCounties.length/cols);
		
		this.countiesDiv.style.width= Math.max(cols*110,340)+'px';

		var t1,t2;
		for(var i=0;i<rows;i++){
			a.push('<tr>')
			
			for (var x=0; x< cols; x++)
				if (i+(x*rows) < tempCounties.length){
					t1=t2="";
					if(optObj.defaultCounties && optObj.defaultCounties.indexOf(tempCounties[i+(x*rows)].COUNTY_ID)>-1){
						t1=' idxSel';
						t2=' checked ';
					}
					a.push('<td><div class="idxChkBx iraCounty'+t1+'" title="'+tempCounties[i+(x*rows)].COUNTY+'" style="width:105px"><input type="checkbox" name="county_ids" value="'+tempCounties[i+(x*rows)].COUNTY_ID+'"'+t2+'>'+tempCounties[i+(x*rows)].COUNTY+'</div></td>')
				}
			a.push('</tr>')
		}
		a.push('</table></form>')
		this.countiesDiv.innerHTML = a.join('');
		
		Event.observe(this.countiesDiv.getElementsByClassName('idxCitiesTable')[0],'click',
			function(e){
				this.check(e);
				this.countiesText();
			}.bindAsEventListener(this));

		//Event.observe($('chkAllCounties'),'click',this.allCounties.bind(this,true))
		//Event.observe($('unChkAllCounties'),'click',this.allCounties.bind(this,false))
		var x = this.iCounties
		var top = x.offsetHeight-1;
		var left = x.offsetWidth-this.countiesDiv.offsetWidth;
		
		while (x && x.tagName != 'HTML'){
			left += x.offsetLeft;
			top += x.offsetTop
			x = x.offsetParent;
		}
		if (left < 0)
			left = (this.windowWidth - 735)/2;
		this.countiesDiv.style.top = top+'px'
		this.countiesDiv.style.left = left+'px'
	}

	/*this.allCounties = function(b){
		var x = this.countiesDiv.getElementsByTagName('td')
		for (var i=0;i<x.length;i++){
			if(x[i].firstChild.firstChild.type == 'checkbox')
				x[i].firstChild.firstChild.checked = b;
			(b) ? $(x[i].firstChild).addClassName('idxSel') : $(x[i].firstChild).removeClassName('idxSel')
		}
		this.countiesText();
	}*/
	


	this.testSpan.style.fontSize = this.iCities.getStyle('font-size');
	this.testSpan.style.padding = this.iCities.getStyle('padding');
	this.testSpan.style.fontFamily = this.iCities.getStyle('fontFamily');
	this.testSpan.style.fontWeight = this.iCities.getStyle('fontWeight');

	/*this.allCities = function(b){
		var x = this.citiesDiv.getElementsByTagName('td')
		for (var i=0;i<x.length;i++){
			$(x[i].firstChild)
			if(x[i].firstChild.firstChild.type == 'checkbox')
				x[i].firstChild.firstChild.checked = b;
			(b) ? x[i].firstChild.addClassName('idxSel') : x[i].firstChild.removeClassName('idxSel')
		}
		this.citiesText();
	}*/

	
	
	this.cities = function(e){
		var a;
		if (!this.citiesDiv){
			this.citiesDiv = $(document.createElement('div'))
			this.citiesDiv.className = 'idxCitiesDiv';
			document.body.appendChild(this.citiesDiv)
		}
		else
			if(this.citiesDiv.style.visibility=='visible')
				return;
		
		if (this.cityCounties != this.selectedCounties.join(',')){
			if(this.citiesDiv.innerHTML == ''){
				var a=[];
				a.push('<div class="idxCitiesHdr">');
				a.push('<div style="float:right;margin-top:4px"><button id="closeCities">Continue</button></div>');
				//a.push('<div class="idxBut" id="closeCities" style="margin-right:0px">&nbsp;<img src="/wwwroot/t/tricityidx/images/close_small.gif" style="margin-left:0px"></div>');
				//a.push('<img id="unChkAllCities" class="idxBut" style="margin-right:4px" src="/wwwroot/t/tricityidx/images/uncheckall.gif">');
				//a.push('<img id="chkAllCities"  class="idxBut" src="/wwwroot/t/tricityidx/images/checkall.gif">');
				a.push('</div><form name="idxCitiesForm" id="idxCitiesForm" style="margin:0px"></form>');
				this.citiesDiv.innerHTML = a.join('');

				var form = this.citiesDiv.getElementsByTagName('form')[0];
				Event.observe(form,'click',this.bCheck);
				//Event.observe($('chkAllCities'),'click',this.allCities.bind(this,true))
				//Event.observe($('unChkAllCities'),'click',this.allCities.bind(this,false))
			}
			else 
				var form = this.citiesDiv.getElementsByTagName('form')[0];
					
			a=['<table class="idxCitiesTable" cellpadding="0" cellspacing="0">'];
			var tempCities = []
			var tempCounty = "";
			for (var i=0;i<iraCities.length;i++) {
				if (this.selectedCounties.indexOf(iraCities[i].COUNTY_ID)>-1){
					if (iraCities[i].COUNTY_ID != tempCounty){
						tempCounty = iraCities[i].COUNTY_ID;
						tempCities.push(iraCountiesX[iraCities[i].COUNTY_ID])
					}
					if (vCities[iraCities[i].CITY_ID]) {
						tempCities.push(iraCities[i]);
					}
				}
			}
			
			var cols = Math.max(Math.min(7,Math.ceil(Math.sqrt(tempCities.length))-2),1)

			this.citiesDiv.style.width= Math.max(cols*110,340)+'px';
				
			var rows=Math.ceil(tempCities.length/cols);
			var t1,t2;

			for(var i=0;i<rows;i++){
				a.push('<tr>')
				for (var x=0; x< cols; x++)
					if (i+(x*rows) < tempCities.length){
						t1=t2='';
						
						if(this.selectedCities.indexOf(tempCities[i+(x*rows)].CITY_ID)>-1){
							t1=' idxSel';
							t2=' checked ';
						}
						if (tempCities[i+(x*rows)].COUNTY) {
							a.push('<td><div class="idxChkBx idxCounty" title="'+tempCities[i+(x*rows)].COUNTY+' County\nClick to select/unselect entire County" style="width:110px"><input type="checkbox" value="'+tempCities[i+(x*rows)].COUNTY_ID+'">'+tempCities[i+(x*rows)].COUNTY+' CO.</div></td>')
						} else {
							a.push('<td><div class="idxChkBx'+t1+'" title="'+tempCities[i+(x*rows)].CITY+'" style="width:110px"><input type="checkbox" name="city_ids"'+t2+' value="'+tempCities[i+(x*rows)].CITY_ID+'">'+tempCities[i+(x*rows)].CITY+'</div></td>')
						}
					}
				a.push('</tr>')
			}
			
			a.push('</table>')
			
			form.innerHTML = a.join('');
			this.cityCounties = this.selectedCounties.join(',');
			
			var left = (this.windowWidth - parseInt(this.citiesDiv.style.width))/2;
			x = this.iCities
			var top = x.offsetHeight-1;
			var left = x.offsetWidth-this.citiesDiv.offsetWidth;
			while (x && x.tagName != 'HTML'){
				top += x.offsetTop
				left += x.offsetLeft
				x = x.offsetParent;
			}
			if (left < 0)
				left = (this.windowWidth - 735)/2;
			this.citiesDiv.style.top = top+'px'
			this.citiesDiv.style.left = left+'px'
		}


		
		this.citiesDiv.style.visibility='visible';
		if (window.pageYOffset)	{
			  this.citiesDiv.scTop = window.pageYOffset
			  this.citiesDiv.scLeft = window.pageXOffset
		}
		else if (document.documentElement && document.documentElement.scrollTop)	{
			this.citiesDiv.scTop = document.documentElement.scrollTop
			this.citiesDiv.scLeft = document.documentElement.scrollLeft
		}
		else if (document.body){
			  this.citiesDiv.scTop = document.body.scrollTop
			  this.citiesDiv.scLeft = document.body.scrollLeft
		}
		//alert(parseInt(this.citiesDiv.style.top))
		
		if ((parseInt(this.citiesDiv.style.top)+this.citiesDiv.offsetHeight)-this.citiesDiv.scTop > this.windowHeight)
			window.scroll(0,((parseInt(this.citiesDiv.style.top)+this.citiesDiv.offsetHeight))-this.windowHeight)
		Event.stop(e);
	}
	
	
	this.counties = function(e){
		if (!window.vCounties){
			setTimeout(function(){this.counties()}.bind(this),20)
			if (e)
				Event.stop(e)
			return;
		}
		
		if (!this.countiesDiv)
			this.createCountiesDiv();
			
		if (this.countiesDiv.style.visibility=='visible')
			return;
			
		this.countiesDiv.style.visibility='visible';
		if (window.pageYOffset)	{
			  this.countiesDiv.scTop = window.pageYOffset
			  this.countiesDiv.scLeft = window.pageXOffset
		}
		else if (document.documentElement && document.documentElement.scrollTop)	{
			this.countiesDiv.scTop = document.documentElement.scrollTop
			this.countiesDiv.scLeft = document.documentElement.scrollLeft
		}
		else if (document.body){
			  this.countiesDiv.scTop = document.body.scrollTop
			  this.countiesDiv.scLeft = document.body.scrollLeft
		}
		if ((parseInt(this.countiesDiv.style.top)+this.countiesDiv.offsetHeight)-this.countiesDiv.scTop > this.windowHeight)
			window.scroll(0,((parseInt(this.countiesDiv.style.top)+this.countiesDiv.offsetHeight))-this.windowHeight)
		if(this.citiesDiv && this.citiesDiv.style.visibility=='visible')
			this.citiesDiv.style.visibility = 'hidden'
		if (e)
			Event.stop(e)
	}
	
	
	
	
	
	
	
	Event.observe(this.iCities,'click',this.cities.bindAsEventListener(this))
	Event.observe(this.ciImg,'click',this.cities.bindAsEventListener(this))
	
	Event.observe(this.iCounties,'click',this.counties.bindAsEventListener(this))
	Event.observe(this.coImg,'click',this.counties.bindAsEventListener(this))
	this.positionArrows = function() {
		try {
			var iCitiesPos = $(this.iCities).positionedOffset();
			var iCountiesPos = $(this.iCounties).positionedOffset();
			
			var top = iCitiesPos.top+1;
			var left = iCitiesPos.left + parseInt(this.iCities.getStyle('width')) - parseInt(this.ciImg.getStyle('width'))+5;
	
			this.ciImg.style.top = top+'px';
			this.ciImg.style.left = left+'px';
			
			var top = iCountiesPos.top+1;
			var left = iCountiesPos.left + parseInt(this.iCities.getStyle('width')) - parseInt(this.coImg.getStyle('width'))+5;
	
			this.coImg.style.top = top+'px';
			this.coImg.style.left = left+'px';
		} catch(e) {
			var top = 1;
			var left = this.iCities.offsetWidth - this.ciImg.offsetWidth
		
			x=this.iCities;
			while (x && x.tagName != 'HTML'){
				top += x.offsetTop
				left += x.offsetLeft
				x = x.offsetParent;
			}
			this.ciImg.style.top = top+'px';
			this.ciImg.style.left = left+'px';
			
			var top = 1;
			var left = this.iCounties.offsetWidth - this.coImg.offsetWidth
			x=this.iCounties;
			while (x && x.tagName != 'HTML'){
				top += x.offsetTop
				left += x.offsetLeft
				x = x.offsetParent;
			}
			this.coImg.style.top = top+'px';
			this.coImg.style.left = left+'px';
		}
	}
	
	this.positionArrows();
	Form.focusFirstElement($('searchForm'));

	
	this.citiesText = function(theSelectedCities){
		var cities2=[];
		var a;

		if (!theSelectedCities){
			var city_ids = $('idxCitiesForm').city_ids;
			this.selectedCities=[];
			if (!city_ids.length){
				if (city_ids.checked) {
					this.selectedCities.push(city_ids.value)
				}
			}
			else
				for (var i=0;i<city_ids.length;i++){
					if (city_ids[i].checked) {
						// FIX: added parseInt(), this was a hard to find issue which made Firefox not work properly
						this.selectedCities.push(parseInt(city_ids[i].value));
					}
				}
		}
		else
			this.selectedCities = theSelectedCities;
			
		this.testSpan.innerHTML='';
		for (var i=0;i<iraCities.length;i++) {
			
			if(this.selectedCities.indexOf(iraCities[i].CITY_ID)>-1){
				cities2.push(iraCities[i].CITY)
				this.testSpan.innerHTML = cities2.join(',')
				if(this.testSpan.offsetWidth>324){
					break;
				}
			}
		}
		a = this.testSpan.innerHTML.split('');
		while (this.testSpan.offsetWidth>326){
			a.pop()
			this.testSpan.innerHTML = a.join('')+'...' 
		}
		this.iCities.value=this.testSpan.innerHTML;
	
	}
	this.countiesText = function(){
		if ($('idxCountiesForm')){
			var county_ids = $('idxCountiesForm').county_ids;
		} else {
			var county_ids = [];
			for (var i=0;i<optObj.defaultCounties.length;i++) {
				county_ids.push({checked:true,value:optObj.defaultCounties[i]});
			}
		}
				
		this.selectedCounties=[];
		var counties2=[];
		var a;
		
		for (var i=0;i<county_ids.length;i++){
			if (county_ids[i].checked) {
				// FIX: added parseInt(), this was a hard to find issue which made Firefox not work properly
				this.selectedCounties.push(parseInt(county_ids[i].value));
			}
		}
		this.testSpan.innerHTML='';

		for (var i=0;i<iraCounties.length;i++) {
			if(this.selectedCounties.indexOf(iraCounties[i].COUNTY_ID)>-1){
				counties2.push(iraCounties[i].COUNTY);
				this.testSpan.innerHTML = counties2.join(',')
				if(this.testSpan.offsetWidth>324){
					break;
				}
			}
		}
		a = this.testSpan.innerHTML.split('');
		while (this.testSpan.offsetWidth>326){
			a.pop()
			this.testSpan.innerHTML = a.join('')+'...' 
		}
		this.iCounties.value=this.testSpan.innerHTML
	
	}
	
	if (optObj.defaultCounties)
		this.countiesText();

		
		
	this.chkCounty = function(county_ids){
		var tds = this.citiesDiv.getElementsByTagName('td')
		var countyObj;
		var countyId
		var unchecked = false;
		
		for (var x=0;x<county_ids.length;x++){
			unchecked=false;
			for (var i=0;i<tds.length;i++){
				if ($(tds[i].firstChild).hasClassName('idxCounty'))
					countyId = tds[i].firstChild.firstChild.value
				else
					countyId = iraCitiesX[tds[i].firstChild.firstChild.value].COUNTY_ID
	
				if (countyId == county_ids[x]){
					if (tds[i].firstChild.hasClassName('idxCounty')){
						countyObj = tds[i];
					}
					else {
						if (!tds[i].firstChild.firstChild.checked){
							unchecked = true;
						}
					}
				}
				if (countyObj && unchecked){
					break;
				}
			}
			countyObj.firstChild.firstChild.checked = !unchecked;
			!unchecked ? countyObj.firstChild.addClassName('idxSel') : countyObj.firstChild.removeClassName('idxSel')
		}
	}

	
	
	
	this.handleKeys = function(event){
		var src = ($(event.srcElement) || $(event.target))
		if (this.countiesDiv && this.countiesDiv.style.visibility != 'hidden')
			this.countiesDiv.style.visibility = 'hidden';
			
		if (this.citiesDiv && this.citiesDiv.style.visibility !='hidden')
			this.citiesDiv.style.visibility = 'hidden'
			
		var k = event.keyCode;
		if (k==13){
			this.search();
			Event.stop(event);
			return;
		}
		if(event.ctrlKey && k != 17)
			if (k == 88 || k == 86 || k==67)
				return;
		
		var digits = src.getAttribute('digits');
		var decimal = src.getAttribute('decimal') || 0;
		
		if (src.name == 'streetName')
			return;
			
		if (!digits && k!=9){
			Event.stop(event);
			return;
		}

		if (k==39 || k==37 || k==46 || k==8 || k==35 || k==36) //allowed keys
			return;

		src.cursorPos = this.cursorPos(src);
		
		var t = src.value.split('');
		var d=null;
		
		var a = src.value.split('.')
			
		for (var i=0;i<t.length;i++){
			if (t[i]=='.'){
				d=i;
				break;
			}
		}
		
		if (k!=9){
			if (digits && (a.length==1 || d >= src.cursorPos) && a[0].replace(/,/g,  '').length >= digits && k!=190 && !src.selectedLength){
					Event.stop(event)
					return
			}
			if (a.length > 1 && decimal && ((d < src.cursorPos && a[1].replace(/,/g,  '').length >= decimal) || k==190)){
					Event.stop(event)
					return
			}
		
			if (!(k >= 48 && k<=57) && !(k >= 96 && k<=105))
				if (!decimal || k!=190){
					Event.stop(event)
					return
				}
		}
		if(k==9){
			var inputs = this.searchForm.getInputs('text')
			if(src==inputs[0] && event.shiftKey){
				inputs[inputs.length-1].focus()
				Event.stop(event)
				return
			}
			if(src==inputs[inputs.length-1] && !event.shiftKey){
				inputs[0].focus()
				Event.stop(event)
				return
			}
		}
	}


	this.format = function (event) {
		var obj = ($(event.srcElement) || $(event.target))

		if(event.type=='blur' && (obj.id == 'idxCounties' || obj.id == 'idxCities'))
			return;

		if (obj.type != 'text')
			return;
		
		k = event.keyCode
		
		p = this.cursorPos(obj)
		
		if (k==39 || k==37 || p < obj.value.length ) //allowed keys
			return;
		v = obj.value.replace(/,/g,'');
		v += '';
		x = v.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		obj.value = x1 + x2;
	}.bindAsEventListener(this)

	
	this.cursorPos = function test(elm){
		
		var i=elm.value.length+1;
		if (elm.createTextRange){
			theCaret = document.selection.createRange().duplicate();
			elm.selectedLength = theCaret.text.length
			while ( theCaret.parentElement() == elm	&& theCaret.move("character",1)==1 ) 
				--i;
		}
		return  i-1
	}

	
	this.searchForm = $('searchForm')
	var inputs = this.searchForm.getElementsByTagName('input')
	for (var i=0;i<inputs.length;i++)
		if (inputs[i].type == 'text')
			Event.observe(inputs[i],'blur',this.format)
			
	Event.observe(this.searchForm,'keyup',this.format);
	//Event.observe(this.searchForm,'blur',this.format.bindAsEventListener(this));
	Event.observe(this.searchForm,'keydown',this.handleKeys.bindAsEventListener(this));
	Event.observe(this.searchForm,'click',this.check);
	Event.observe(document.body,'click',function(e){
		//setTimeout(function(){
			var dr = this.divRegistry;
			while (dr.length)
				dr.pop().style.visibility = 'hidden'
		//}.bind(this),200)
			//dr[i].style.visibility='hidden'
			
	}.bindAsEventListener(this));
}

