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()})}})};

var query_url = "", isNewSearch = false, isListingRemove = false, totalListings = -1, totalListingsCurPage = 0, resetSelection = false, hasFeatureListing = false, showFeatureListingWindow = false, uniqueProperty = '', maxSelected=20, rowColor = '#FFFFFF', rowHiColor = '#FFE978', rowBorderColor = '#FFFFFF', rowHiBorderColor = '#FFE978', selPageColor = '#FFFFFF', selPageHiColor = '#FFE978', zipPara = '', orderBy = "price", orderDir = "DESC", listing_source = "", selected_home_features= "", selected_comm_features= "";
function Listing(property_id,agent_id){
	this.property_id = property_id; this.agent_id = agent_id; this.title = ""; this.city = ""; this.prop_type = ""; this.bedroom = ""; this.bathroom = ""; this.garage = ""; this.footage = ""; this.pool = ""; this.spa = ""; this.price = ""; this.brokerlogo_sm = ""; this.listing_photo = "";
	this.clear_data = function() {
		this.property_id = ""; this.agent_id = ""; this.city = ""; this.prop_type = ""; this.bedroom = ""; this.bathroom = ""; this.garage = ""; this.footage = ""; this.pool = ""; this.spa = ""; this.price = ""; this.brokerlogo_sm = ""; this.listing_photo = ""; this.listing_office = ""; this.title = "";
	}
	this.copy_data = function(obj) {
		this.property_id = obj.property_id; this.agent_id = obj.agent_id; this.city = obj.city; this.prop_type = obj.prop_type; this.bedroom = obj.bedroom; this.bathroom = obj.bathroom; this.garage = obj.garage; this.footage = obj.footage; this.pool = obj.pool; this.spa = obj.spa; this.price = obj.price; this.brokerlogo_sm = obj.brokerlogo_sm; this.listing_photo = obj.listing_photo; this.listing_office = obj.listing_office; this.title = obj.title;
	}
}

var listingArrayIndex = 0;
var listingArray = new Array(10);

for(var i=0; i<11; i++) {
	listingArray[i] = new Listing("","");
}

var seletedListingArrayIndex = 0;
var selectedListingArray = new Array(20);

for(var i=0; i<20; i++) {
	selectedListingArray[i] = new Listing("","");
}

function ImageLoadFailed(obj) {
	obj.src = "http://www.househunt.org/images/no-photo-01.jpg";
}

function resize_logo() {
	if(img_brokerlogo.height>80) {
		img_brokerlogo.height = 80;
	}
}

function genListingRow(i,obj) {
	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="propCol2">'+
				'<p class="txtPropTitle">'+obj.title+'<\/p>'+
				'<p class="txtPropType">'+obj.prop_type+'<\/p>'+
				'<p class="txtPropLoc">'+obj.city+', '+state_abv+'<\/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 '+obj.footage+' sq.ft.<\/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 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();
		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];
			var 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 afterAjax() {
	rebindBehaviors();
	checkSelectedListings();
	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");
	var listings = xml.getElementsByTagName("listing");
	var 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= '';
		var listingIndex =0;
		var center = null;
		if(typeof GMap2 === "function"){
			center = new GLatLng(schlat,schlng);
		}
		var keywrd = document.forms["searchform"].elements["keyword"].value;
		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[listingIndex].property_id = list_rec[1];
			listingArray[listingIndex].agent_id = list_rec[2];
			listingArray[listingIndex].city = list_rec[4];
			listingArray[listingIndex].prop_type = list_rec[5];
			listingArray[listingIndex].bedroom = list_rec[6];
			listingArray[listingIndex].bathroom = list_rec[7];
			listingArray[listingIndex].garage = list_rec[8];
			listingArray[listingIndex].footage = list_rec[9];
			listingArray[listingIndex].pool = list_rec[10];
			listingArray[listingIndex].spa = list_rec[11];
			listingArray[listingIndex].price = list_rec[12];
			listingArray[listingIndex].brokerlogo_sm = list_rec[13];
			listingArray[listingIndex].listing_photo = list_rec[3];
			listingArray[listingIndex].title = list_rec[18];
			listingArray[listingIndex].listing_office = list_rec[16];
			listingArray[listingIndex].keyword = keywrd;
			listingArray[listingIndex].dist = null;
			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[listingIndex].dist = d.toFixed(2);
				} else {
					listingArray[listingIndex].dist = 'N/A';
				}
			}
			listingRow = genListingRow(listingIndex,listingArray[listingIndex]);
			listing_content += listingRow;
			listingIndex++;
		}
		totalListingsCurPage = listingIndex;
		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 = $("#listing_content");
	var dimPosition = $listingContent.offset();
	var $dim = $('#dim');
	var dimW = $listingContent.width();
	var dimH = $listingContent.height();
	var dimT = dimPosition.top;
	var dimL = dimPosition.left;
	$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);
	var 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;
	if (qry){
		q = qry;
	}	else {
		q = 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);
	var 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();
	var cnt=0;
	var is_removed = false;
	var dcl=document.forms["listingform"].elements["mn_slistings"];
	var 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 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() {
	var el = 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);
			var 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;
		var 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;
	});

	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() {
	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');
	state_abv = document.forms["searchform"].elements["st"].value;
	adjustPage();
	bindBehaviors();
	checkSelectedListings()
}

jQuery(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");
}