jQuery.fn.center=function(absolute){return this.each(function(){var t=jQuery(this);t.css({position:absolute?'absolute':'fixed',left:'50%',top:'50%',zIndex:'200'}).css({marginLeft:'-'+(t.outerWidth()/2)+'px',marginTop:'-'+(t.outerHeight()/2)+'px'});if(absolute){t.css({marginTop:parseInt(t.css('marginTop'),10)+jQuery(window).scrollTop(),marginLeft:parseInt(t.css('marginLeft'),10)+jQuery(window).scrollLeft()})}})};

jQuery.fn.qtip.styles.hfstooltip = {
   background: 'white url(http://idx.househunt.org/househunt/new-page/img/beige_bg.gif)',
   color: '#111',
   textAlign: 'left',
   width: {
      min: 0,
      max: 350
   },
   border: {
      width: 1,
      color: '#999999'
   },
   name: 'defaults'
}

function unique(a) {
   var r = new Array();
   o:for(var i = 0, n = a.length; i < n; i++)
   {
      for(var x = 0, y = r.length; x < y; x++)
      {
         if(r[x]==a[i]) continue o;
      }
      r[r.length] = a[i];
   }
   return r;
}

var query_url = "", isNewSearch = false, totalListings = -1, hasFeatureListing = false, maxSelected=20, orderBy = "price", orderDir = "DESC", listing_source = "", listingArray = [];

var genListingRow = (function () { 
	var state_abv = document.forms["searchform"].elements["st"].value;
	return function (i,obj) {
		var sClass = obj.num_photos <= 1 ? 'hide' : 'caption';
		var listingRow =	'<div class="propRow">'+
					//'<div class="propCol1"><div class="propImgFrame"><div class="propImg"><img src="'+obj.listing_photo+'" width=90  onerror="ImageLoadFailed(this)"><\/div><\/div><\/div>'+
					'<div class="propCol1"><div class="propImgFrame"><div class="propImg"><img src="'+obj.listing_photo+'" width="90" onerror="ImageLoadFailed(this)"\/><cite class="'+sClass+'">'+obj.num_photos+' Photos<\/cite><\/div><\/div><input type="checkbox" id="prop_chkbox'+i+'" value="' + obj.agent_id + '-' + obj.property_id + '"  name="prop_list" \/>Select<\/div>'+
					'<div class="propCol2">'+
					'<p class="txtPropTitle">'+obj.title+'<\/p>';


		if(show_mls_id == 'y'){
			listingRow += '<p class="txtPropType">MLS# '+obj.property_id;
		}

		if(show_status == 'y'){
			listingRow += '&nbsp;&nbsp;&nbsp;Status: Active';
		}

		if(show_mls_id == 'y'){
			listingRow += '<\/p>';
		}

		listingRow += '<p class="txtPropType">'+obj.prop_type+'<\/p>'+
					'<p class="txtPropLoc">'+obj.city+', '+state_abv+' '+obj.zip_code +'<\/p>';
					
		if(obj.keyword !== null){
				listingRow +='<p class="txtPropKeyword">'+obj.keyword+'<\/p>';
		}
		if(obj.dist !== null){
			listingRow +='<p class="txtPropType">Distance : '+obj.dist+' miles<\/p>';
		}
		//listingRow +=	'<p class="txtPropSelect"><input type="checkbox" id="prop_chkbox'+i+'" value="' + obj.agent_id + '-' + obj.property_id + '"  name="prop_list" \/>Select this listing<\/p>';
		listingRow +=	'<\/div>'+
					'<div class="propCol3">'+
					'<p class="txtPropPrice">'+obj.price+'<\/p>'+
					'<p class="txtPropBasic">'+obj.bedroom +' Bd, '+obj.bathroom+' Ba ';
					
		if(show_sqft != 'n'){
			listingRow +=  obj.footage+' sq.ft.';
		}
		
		listingRow +=  '<\/p>'+
					'<p class="idxLogo">'+obj.brokerlogo_sm +'<\/p>';
		if(show_office == 'y'){
			listingRow +=	'<p class="txtOffice">'+obj.listing_office +'<\/p>';
		}
		listingRow += '<\/div><\/div>';
		return listingRow;
	}
})();

function createPageLnk(page_no,status,text) {
	var txt = text || page_no;
	var clss = status == 1 ? '"pageNo"' : '"pageNo0"';
	return '<a class=' + clss + ' href="#rec'+ ((page_no-1)*10) +'">'+txt+'<\/a>';
}

function showPageNav(num_records,rec_no) {
	var page_no=0, page_nav_html = "", max_nav = 7, page_max = 0, page_list = ["","","","","","","","","","","","","","",""];
	var mid_pos = (max_nav+1)/2;
	page_no = (rec_no/10)+1;
	page_max = Math.ceil(num_records/10);
	if(page_max<max_nav) {
		max_nav = page_max;
	}
	if(page_no<=max_nav) {
		for(var i=1; i<=max_nav; i++) {
			//alert(page_no +'=='+ i);
			if(page_no == i) {
				page_list[i-1] = createPageLnk(i,0);
			} else {
				page_list[i-1] = createPageLnk(i,1);
			}
		}
	}
	if(page_max>max_nav) {
		page_list[max_nav-2] = '<span class="currentPage">...<\/span>';
		page_list[max_nav-1] = createPageLnk(page_max,1);
	}
	if(page_no>=6) {
		page_list[0] = createPageLnk(1,1);
		page_list[1] = '<span class="currentPage">...<\/span>';
		for(var i=2; i<mid_pos; i++) {
			page_list[i] = createPageLnk(page_no-(mid_pos-i)+1,1);
		}
		page_list[mid_pos-1] = createPageLnk(page_no,0);
		for(var i=mid_pos; i<max_nav-2; i++) {
			page_list[i] = createPageLnk(page_no+i-mid_pos+1,1);
		}
		page_list[max_nav-2] = '<span class="currentPage">...<\/span>';
		page_list[max_nav-1] = createPageLnk(page_max,1);
	}
	if(page_no >= (page_max-4) && page_max>max_nav) {
		for(var i=max_nav; i>1; i--) {
			var page_idx = page_max-max_nav+i;
			if(page_no == page_idx) {
				page_list[i-1] = createPageLnk(page_idx,0);
			} else {
				page_list[i-1] = createPageLnk(page_idx,1);
			}
		}
		page_list[1] = '<span class="currentPage">...<\/span>';
	}
	for(var i=0; i<max_nav; i++) {
		//alert(i+'='+page_list[i]);
		page_nav_html +=  page_list[i] + '&nbsp;&nbsp;';
	}
	var previous_page = "";
	if(page_no>1) {
		previous_page = createPageLnk(page_no-1,1,'&nbsp;&laquo; Previous&nbsp;');
		previous_page += '&nbsp;&nbsp;';
	}
	var next_page = "";
	if(page_no<page_max) {
		next_page = createPageLnk(page_no+1,1,'&nbsp;Next &raquo;&nbsp;');
	}
	page_nav_html = previous_page + page_nav_html + next_page;
	jQuery('#navMsg1').html('Found '+totalListings+' homes');
	jQuery('#pageNav1, #pageNav2').html(page_nav_html);
}

function loadSelected() {
	//user may be select checkbox before javascript loaded
	var dom = document.forms["listingform"].elements["mn_slistings"];
	var sListings = dom.value, aSlc = jQuery("input[name=prop_list]:checked").serializeArray();
	if (aSlc.length !== 0) {
		aSlc = jQuery.map(aSlc, function(o, i){ return o.value;});
		aSlc = aSlc.concat(sListings.split(','));
		aSlc = unique(aSlc);
		dom.value = aSlc.join(',');
	}
}

function checkSelectedListings() {
	var listings = document.forms["listingform"].elements["mn_slistings"].value;
	if (listings != "") {
		var chkboxs = jQuery('#listingform').find('input[type="checkbox"]');
		if (chkboxs.size() != 0) {
			var addArray = listings.split(",");
			if (addArray.length != 0){
				chkboxs.val(addArray).each(function(){
					if(this.checked) {
						jQuery(this).parents('div.propRow').css('backgroundColor', '#DDD');
					}
				});
				jQuery('#viewSelected p:first').text('You select ' + addArray.length + ' listing(s)');
			}
		}
	}
}

function changeTitle() {
	var sTitle = document.title, $terrtitle = jQuery('#terrTitle>h1'), $terrbreadcrumbs = jQuery('#terrbreadcrumbs'), $terrHeadline = jQuery('#terrHeadline>h2');
	var sTerrTitle = $terrtitle.text(), sTerrbreadcrumbs = $terrbreadcrumbs.html(), sMidHeader = 'Real Estate Listings', sTerrHeadline = $terrHeadline.text();
	if (keyword !== '') {
		var sKeyword = jQuery('#keyword').val();
		
		if(sKeyword == '') {
			sKeyword = 'All';
		}
		sTitle = sTitle.replace(/^(.*) - Real Estate (.*)$/, sKeyword+" - Real Estate "+"$2");
		sTerrHeadline = sTerrHeadline.replace(/^(.*) - Real Estate (.*)$/, sKeyword+" - Real Estate "+"$2");
		sTerrTitle = sTerrTitle.replace(/^(.*) Properties for (.*)$/, sKeyword+" Properties for "+"$2");
		sTerrbreadcrumbs = sTerrbreadcrumbs.replace(/\n/g, '').replace(/^(.*) &gt; (.*)$/, "$1 "+' &gt; '+sKeyword+" Properties <br \/>");
		sMidHeader = sKeyword+" - Real Estate Listings";
		if (keyword !== sKeyword) {
			jQuery('#featListing').hide();
			keyword = sKeyword;
		}
	} else if (zip_code !== '') {
		var sZip =  jQuery('#zip_code').val();
		sTitle = sTitle.replace(/\d{5}/g, sZip);
		sTerrTitle =sTerrTitle.replace(/\d{5}/, sZip);
		sTerrHeadline = sTerrHeadline.replace(/\d{5}/,sZip);
		sTerrbreadcrumbs = sTerrbreadcrumbs.replace(/\n/g, '').replace(/\d{5}/, sZip);
		sMidHeader = sZip+" Real Estate Listings";
		if (zip_code !== sZip) {
			jQuery('#featListing').hide();
			zip_code = sZip;
		}
	} else if (type !== '') {
		var id = jQuery('#type').val();
		if (id !== '') {
			var Types = {'01': 'Single Family Home', '02': 'Townhome - Condo', '03': 'Investment Property', '04': 'Vacant Land'};
			var sType = Types[id], regexS = Types[type];
			var regex = new RegExp(regexS, "ig");
			sTerrbreadcrumbs = sTerrbreadcrumbs.replace(regex, sType);
			sTitle = sTitle.replace(regex, sType);
			sTerrTitle = sTerrTitle.replace(regex, sType);
			sTerrHeadline = sTerrHeadline.replace(regex, sType);
			sMidHeader = sType+" Real Estate Listings";
			if (type !== id) {
				jQuery('#featListing').hide();
				type = id;
			}
		}
	}
	$terrbreadcrumbs.html(sTerrbreadcrumbs);
	document.title = sTitle;
	$terrtitle.text(sTerrTitle);
	$terrHeadline.text(sTerrHeadline);
	jQuery('#listingHeader').text(sMidHeader);
}

function setTooltips(){
	var regNum=/^(\d+)? Photos/i, regBd=/Bd/, regBa=/Ba/, regSqft=/sq.ft./, regNoPhoto=/no-photo-01.jpg$/;
	jQuery('div.propImgFrame').each(function(i){
		var $self = $(this), $img = $self.find('img'), $row = $self.parents('div.propRow'), $target = $row.find('div.propCol1'), sInfo='', locInfo='', sNumPhotos='', sClass='caption';
		if (!listingArray[i]) {
			sNumPhotos = $self.find('cite').text();
			sNumPhotos = sNumPhotos.replace(regNum, "$1");
			if (sNumPhotos === '') {sNumPhotos = '0';}
			listingArray[i] = {
				listing_photo: $img.attr('src'),
				price: $row.find('p.txtPropPrice').text(),
				title: $row.find('p.txtPropTitle').text(),
				num_photos: parseInt(sNumPhotos)
			};
			sInfo = $row.find('p.txtPropBasic').text();
			sInfo = sInfo.replace(regBd, 'beds').replace(regBa, 'baths').replace(regSqft, 'sqft.');
			locInfo = $row.find('p.txtPropLoc').text();
		} else {
			sInfo = listingArray[i].bedroom+' beds '+listingArray[i].bathroom+' baths '+listingArray[i].footage+' sqft.';
			locInfo = listingArray[i].city+' '+listingArray[i].zip_code;
		}
		if (listingArray[i].num_photos <= 1 || regNoPhoto.test(listingArray[i].listing_photo)) {
			sClass = 'hide';
			$img.next('cite').addClass('hide');
		}
		var content = ['<div class="propToolTip">',
		'<div class="propToolTipImg"><img src="', listingArray[i].listing_photo, '" width="320" onerror="ImageLoadFailed(this)"\/><cite class="', sClass, '">', listingArray[i].num_photos,	' Photos<\/cite><\/div>',
		'<table width="320">',
			'<tr>',
				'<td style="padding-top:5px; padding-left:3px; padding-right:3px; text-align:left;"><b>', locInfo, '<\/b><\/td>',
				'<td style="padding-top:5px; text-align:right;"><b>', listingArray[i].price, '<\/b><\/td>',
			'<\/tr>',
			'<tr>',
				'<td style="padding-bottom:5px;padding-left:3px;padding-right:3px;text-align:left;">', sInfo, '<\/td>',
				'<td style="padding-bottom:5px;padding-left:3px;padding-right:3px;"><\/td>',
			'<\/tr>',
			'<tr>',
				'<td colspan=2 style="padding-top:5px; padding-bottom:5px;padding-left:3px;padding-right:3px;text-align:left;">', listingArray[i].title, '<\/td>',
			'<\/tr>',
		'<\/table><\/div>'].join('');

		$self.qtip({
         content: content,
         position: {
				adjust: { screen: true },
            corner: {
               target: 'topRight'
            },
				target: $target
         },
			show: {
				delay: 0,
				effect: {
					type: '',
					length: 0
				}
			},
			hide: {
				delay: 0,
				effect: {
					type: '',
					length: 0
				}
			},
         style: 'hfstooltip'
      });
	});
}

function afterAjax() {
	rebindBehaviors();
	checkSelectedListings();
	setTooltips();
	if (keyword !== '' || zip_code !=='' || type !=='') {
		changeTitle();
	}
}

function handleHttpResponse(xml) {
  	totalListings = parseInt(xml.getElementsByTagName("listing_summary")[0].getAttribute("num_records"));
	if(totalListings==0 && hasFeatureListing) {
		totalListings = 1;
	}
	showPageNav(totalListings,parseInt(xml.getElementsByTagName("listing_summary")[0].getAttribute("rec_no")));
	var column_header = xml.getElementsByTagName("column_header"),
		listings = xml.getElementsByTagName("listing"),
		cur_listing_source = xml.getElementsByTagName("listing_source")[0].firstChild.data;
	if(listing_source != cur_listing_source && cur_listing_source !="--") {
		listing_source = cur_listing_source;
	}
	if(listings.length>0 || hasFeatureListing) {
		var listing_content= '', center = null, keywrd = document.forms["searchform"].elements["keyword"].value;
		if(typeof GMap2 === "function"){
			center = new GLatLng(schlat,schlng);
		}
		for (var i = 0, j=listings.length; i < j; i++) {
			var list_rec= listings[i].firstChild.data.split("\t");
			if(hasFeatureListing) {
				if(featureListing.agent_id==list_rec[2] && featureListing.property_id==list_rec[1]){
					continue;
				}
			}
			listingArray[i] = {
				property_id: list_rec[1],
				agent_id: list_rec[2],
				city: list_rec[4],
				prop_type: list_rec[5],
				bedroom: list_rec[6],
				bathroom: list_rec[7],
				garage: list_rec[8],
				footage: list_rec[9],
				pool: list_rec[10],
				spa: list_rec[11],
				price: list_rec[12],
				brokerlogo_sm: list_rec[13],
				listing_photo: list_rec[3],
				title: list_rec[18],
				listing_office: list_rec[16],
				zip_code: list_rec[19],
				num_photos: 0,
				keyword: keywrd,
				dist: null
			};
			if (list_rec[20] !== '') {listingArray[i].num_photos = parseInt(list_rec[20]);}
			if(center !== null) {
				if(list_rec[14] != 0 && list_rec[15] != 0){
					var d = center.distanceFrom(new GLatLng( list_rec[14], list_rec[15] ));
					d *= 0.000621371192;
					listingArray[i].dist = d.toFixed(2);
				} else {
					listingArray[i].dist = 'N/A';
				}
			}
			var sListingRow = genListingRow(i,listingArray[i]);
			listing_content += sListingRow;
		}
		jQuery("#listing_content").html(listing_content);
		adjustPage();
		afterAjax();
	} else {
		jQuery("#listing_content").html('<table><tr><td class="blktxtbld11" style="text-align:left;"><br\/><br\/>No properties found. Please change your criteria.<\/b><br\/><br\/><br\/>Even though no properties matched my criteria,<br\/>please send listings on homes/condos in the surrounding areas.<br\/><br\/><br\/><br\/><br\/><\/td><\/tr><\/table>');
	}
	isNewSearch = false;
}

function showLoadingMsg(){
	var $listingContent = jQuery("#listing_content");
	var dimPosition = $listingContent.offset();
	var dimW = $listingContent.width(), dimH = $listingContent.height(), dimT = dimPosition.top, dimL = dimPosition.left;
	jQuery('#dim').css({'width': dimW, 'height': dimH, 'top': dimT, 'left': dimL, 'opacity': 0.8}).show();
	jQuery('#loader_msg').center(true).show();
}

function readData(url) {
	var elemListingForm = document.forms["listingform"].elements, elemSearchForm = document.forms["searchform"].elements;
	elemListingForm["minprice"].value = elemSearchForm["price1"].value;
	elemListingForm["maxprice"].value = elemSearchForm["price2"].value;
	elemListingForm["min_br"].value = elemSearchForm["bedroom1"].value;
	elemListingForm["min_ba"].value = elemSearchForm["bathroom1"].value;
	elemListingForm["prop_type"].value = elemSearchForm["type"].value;
	elemListingForm["zip_code"].value = elemSearchForm["zip_code"].value;
	elemListingForm["keyword"].value = elemSearchForm["keyword"].value;
	//alert(document.listingform.minprice.value);

  jQuery.ajax({
	beforeSend: showLoadingMsg,
	complete: function () {
		jQuery('#dim, #loader_msg').hide();
	},
	url: url,
	success: handleHttpResponse,
	dataType: 'xml',
	error: function () {
		alert("Can not receive data from server");
	}
  });
}

function goToPage(page_no) {
	currentPage = page_no;
	var rec_no = (page_no-1)*10;
	if(isNewSearch) {
		readData(query_url + '&rec=' + rec_no + '&order_by='+ orderBy + '&order_dir='+ orderDir);
	} else {
		readData(query_url + '&rec=' + rec_no + '&order_by='+ orderBy + '&order_dir='+ orderDir + '&cnt_recs=' +totalListings);
	}
}

function setOrder(str) {
	var order_str = str.split(" ");
	orderBy = order_str[0];
	orderDir = order_str[1];
	var a = jQuery('#searchform').serialize();
	var price1 = getURLParam('price1', a), price2 = getURLParam('price2', a);
	query_url = 'agent_id='+ document.forms["listingform"].elements["mls_agent_id"].value + '&price='+ price1 + ','+ price2+'&'+a;
	query_url = searchUrl + query_url;
	goToPage(currentPage);
}

function setOrderBy(str) {
	if(orderBy != str) {
		orderBy = str;
	} else {
		orderDir = orderDir == 'ASC' ? 'DESC' : 'ASC';
	}
	goToPage(currentPage);
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function storeQuery(qry) {
	var q = qry || jQuery('#searchform').serialize();
	q = q.replace(/=/g, '::');
	createCookie('q', q);
}

function submitSearch(page_no) {
	isNewSearch = true;
	var a = jQuery('#searchform').serialize();
	var price1 = getURLParam('price1', a), price2 = getURLParam('price2', a);
	query_url = 'agent_id='+ document.forms["listingform"].elements["mls_agent_id"].value + '&price='+ price1 + ','+ price2+'&'+a;
	storeQuery(query_url);
	query_url = searchUrl + query_url;
	goToPage(page_no);
}

function addListing(prop_obj, from_chkbox) {
	//prop_obj is jQuery obj.
	var propid = prop_obj.val(),
	cnt=0,
	is_removed = false,
	dcl=document.forms["listingform"].elements["mn_slistings"],
	a = [];
	if (dcl.value != ""){
		var addArray = dcl.value.split(",");
		var add_array_length = addArray.length;
		for (var i=0; i<add_array_length; i++) {
			if (addArray[i] != propid) {
				if (addArray[i] !="") {
					cnt = a.push(addArray[i]);
				}
			} else {
				if (!from_chkbox) {
					prop_obj.attr("checked", false);
				}
				prop_obj.parents('div.propRow').css('backgroundColor', '#FFF');
				is_removed = true;
			}
		}
	}
	if(!is_removed) {
		if(add_array_length>=maxSelected) {
			alert("You have reached the limit of " + maxSelected+ " selections.\n\nPlease complete the form below, in order to view detials of selected properties.");
			prop_obj.attr("checked", false);
			return;
		}
		cnt = a.push(propid);
		if (!from_chkbox) {
			prop_obj.attr("checked", true);
		}
		prop_obj.parents('div.propRow').css('backgroundColor', '#DDD');
	}
	dcl.value = a.join(',');
	jQuery('#viewSelected > p').text('You select ' + cnt + ' listing(s)');
}

function loadNeighborhood() {
	var city;
	$("#city option:selected").each(function() {
		city = $(this).val();
	});	  
	var arrCity = city.split('|');
	$.get('/pages/hhorg/cgibin/househunt/new-page/neighborhood_list.cgi?type=N&terr_id='+arrCity[0],
		function(data) {
			var arrData = data.split("\n");
			var output = [];
			output.push('<option value="">All</option>');
			for (var i=0; i<arrData.length; i++) {
				if(arrData[i] != "") {
					output.push('<option value="'+arrData[i]+'">'+arrData[i]+'</option>');
				}
			}
			$('#neighborhood').html(output.join(''));
		});		
}

function loadSubdivision() {
	var city;
	$("#city option:selected").each(function() {
		city = $(this).val();
	});	  
	var arrCity = city.split('|');
		
	var neighborhood;
	$("#neighborhood option:selected").each(function() {
		neighborhood = $(this).val();
	});	  
		
	$.get('/pages/hhorg/cgibin/househunt/new-page/neighborhood_list.cgi?type=S&terr_id='+arrCity[0]+'&search_name='+neighborhood,
		function(data) {
			var arrData = data.split("\n");
			var output = [];
			output.push('<option value="">All</option>');
			for (var i=0; i<arrData.length; i++) {
				if(arrData[i] != "") {
					output.push('<option value="'+arrData[i]+'">'+arrData[i]+'</option>');
				}
			}
			$('#subdivision').html(output.join(''));
		});		
}

function adjustPage() {
	var listBot = parseInt(document.getElementById('lastBlock').offsetHeight)+parseInt(document.getElementById('lastBlock').offsetTop)+380;
	if(listBot>1400) {
		document.getElementById('contentWrapper').style.height = listBot+'px';
	}
}

function rebindBehaviors() {
	jQuery('a.pageNo').unbind().hover(
		function(){
			jQuery(this).css({backgroundColor: '#FFE978', cursor: 'pointer'});
		},
		function(){
			jQuery(this).css({backgroundColor: '#FFF'});
		}
	);
}

function bindBehaviors() {
	jQuery('#pageNav1, #pageNav2').click(function(e){
		var el = jQuery(e.target);
		if (el.is('a.pageNo')) {
			var sRec = el.attr('href');
			var aRec = sRec.match(/#rec(\d+)$/);
			var rec = (aRec === null) ? getURLParam('rec', sRec) : aRec[1];
			var a = jQuery('#searchform').serialize();
			var price1 = getURLParam('price1', a), price2 = getURLParam('price2', a);
			var qry = 'agent_id='+ document.forms["listingform"].elements["mls_agent_id"].value + '&order_by='+ orderBy + '&order_dir='+ orderDir + '&rec=' + rec+'&price='+ price1 + ','+ price2+'&'+a;
			jQuery.ajax({
				beforeSend: showLoadingMsg,
				complete: function () {
					jQuery('#dim, #loader_msg').hide();
				},
				url: searchUrl,
				data: qry,
				success: handleHttpResponse,
				dataType: 'xml',
				error: function () {
					alert("Can not receive data from server");
				}
			});
		}
		return false;
	});

	jQuery('#sort_by').show().change(function(){
		setOrder($(this).val());
	});

	jQuery('form#listingform').submit(function(){
		var $lf = jQuery(this);
		if ( $lf.find('input:checked').length != 0 || $lf.find('input[name="mn_slistings"]').val() != '') {
			return true;
		}
		alert('Please select at least one property');
		return false;
	});

	jQuery('#listing_content').click(function(e){
		var from_chkbox = true, el = jQuery(e.target);
		if (!el.is('input[type=checkbox]')) {
			el = el.parents('div.propRow').find('input[type=checkbox]');
			from_chkbox = false;
		}
		addListing(el, from_chkbox);
	});

	jQuery('form#searchform').submit(function(e){
		submitSearch(1);
		return false;
	}).find('input[type=submit]').one('click', function(){
		jQuery('#featListing').hide();
	}).end();

	jQuery('div.propRow').live('mouseover',function(){
		jQuery(this).addClass('hovered');
	}).live('mouseout', function(){
		jQuery(this).removeClass('hovered');
	});
	rebindBehaviors();
}

function getURLParam(name, url) {
	var context = url || window.location.href;
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(context);
	return (results === null ? "" : results[1]);
}

function init() {
	adjustPage();
	setTooltips();
	bindBehaviors();
	loadSelected();
	checkSelectedListings();
	jQuery('#price1').val(price_min);
	jQuery('#price2').val(price_max);
	jQuery('#bedroom1').val(beds_min);
	jQuery('#bathroom1').val(baths_min);
	jQuery('#zip_code').val(zip_code);
	jQuery('#keyword').val(keyword);
	jQuery('#type').val(type);
	storeQuery();
	eraseCookie('lists');
	eraseCookie('navinfo');
}

init();

function OpenScrollingPopup(URL, width, height) {
   var now = new Date();
   var remote = window.open(URL, "popup", "width=" + width + ",height=" + height + ",toolbar=0,location=0,directories=0,resizable=1,status=1,menubar=1,scrollbars=yes");
}