//<![CDATA[
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()})}})};

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 listings = null, 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.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.title = obj.title;
	}
}

var listingArrayIndex = 0;
var listingArray = [];

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

var seletedListingArrayIndex = 0;
var selectedListingArray = [];

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) {
	return '<tr><td>'+'<input type="checkbox" id="prop_chkbox'+i+'" value="' + obj.agent_id + '-' + obj.property_id + '"  name="prop_list" \/><\/td><td>'+obj.city+'<\/td><td>'+obj.prop_type+'<\/td><td>'+obj.bedroom+'<\/td><td>'+obj.bathroom+'<\/td><td>'+obj.footage+'<\/td><td>'+obj.price+'<\/td><\/tr>';
}

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('tr').css('backgroundColor', '#DDD');
				});
				jQuery('#viewSelected > p').text('You select ' + addArray.length + ' listing(s)');
			}
		}
	}
}

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 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 (zip_code !== ''){
		var sZip =  jQuery('#zip_code').val();
		sTitle = sTitle.replace(/\d{5}/, 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 (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");
	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= [], listingIndex =0, $ls = jQuery("#listings > tbody").empty();
		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];
			var listingRow = genListingRow(listingIndex,listingArray[listingIndex]);
			listing_content.push(listingRow);
			listingIndex++;
		}
		totalListingsCurPage = listingIndex;
		var table_body= listing_content.join('');
		$ls.append(table_body);
		adjustPage();
		afterAjax();
	} else {
		var $ls = jQuery("#listings > tbody");
		$ls.append('<tr><td colspan=5><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>');
		//jQuery("#listings").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 $propTable = jQuery("div.propTable"), $dim = jQuery('#dim');
	var dimPosition = $propTable.offset();
	var dimW = $propTable.width(), dimH = $propTable.height(), dimT = dimPosition.top, 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;

  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 readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0, j=ca.length; i < j; i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


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(), 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('tr').removeClass('user-selected');
				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('tr').addClass('user-selected');
	}
	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('#listings').click(function(e){
		var from_chkbox = true;
		var el = jQuery(e.target);
		if (!el.is('input[type=checkbox]')) {
			el = el.parents('tr').find('input[type=checkbox]');
			from_chkbox = false;
		}
		addListing(el, from_chkbox);
	});

	jQuery('form#searchform').submit(function(e){
		submitSearch(1);
		return false;
	});
	
	jQuery('#listings tbody tr').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 setV_ref_id() {
	if(document.forms["listingform"].elements["v_ref_id"]) {
		if(document.forms["listingform"].elements["v_ref_id"].value != '') {
			createCookie('v_ref_id',document.forms["listingform"].elements["v_ref_id"].value,0);
		} else {
			if(readCookie('v_ref_id') != null) {
				document.forms["listingform"].elements["v_ref_id"].value = readCookie('v_ref_id');
			}
		}
	}
	
}

function init() {
	setV_ref_id();
	jQuery('#price1').val(price_min);
	jQuery('#price2').val(price_max);
	jQuery('#bedroom1').val(beds_min);
	jQuery('#bathroom1').val(baths_min);
	jQuery('#type').val(type);
	jQuery('#zip_code').val(zip_code);
	storeQuery();
	eraseCookie('lists');
	eraseCookie('navinfo');
	state_abv = document.forms["searchform"].elements["st"].value;
	adjustPage();
	bindBehaviors();
	loadSelected();
	checkSelectedListings()
}
jQuery(init);
//]]>