function submitSearch() {
	showMsgBox();
	
	query = "";
	
	$("select").each(function () {
		var val = $(this).val();
		if(val!="") {
			var name = $(this).attr("name");
			if(name=='searchBy') { /** Search By **/
				if(val=="location") {
					var keyword = $("input[name=keyword]").attr("value");
					if(keyword) query += "&keyword=" +keyword;
				}
				else query += getMapBoundaryString();
			}
			else query += "&" +name +"=" +val;
		}
	});
	
	/* location List  */
	$("span[class=locListItem]").each(function () {
		var val = $(this).text();
		if(val!="") {
			query += "&locListItem[]=" +val;
		}
	});
	
	/* input can be text box, checkbox, radio */
	$("input[type=checkbox]:checked").each(function () {
		var val = $(this).attr("value");
		if(val!="") {
			var name = $(this).attr("name");
			query += "&" +name +"=" +val;
		}
	});
	
	$("input[type=radio]:checked").each(function () {
		var val = $(this).attr("value");
		if(val!="") {
			var name = $(this).attr("name");
			query += "&" +name +"=" +val;
		}
	});
	
	$("input[type=text]").each(function () {
		var val = $(this).attr("value");
		if(val!="") {
			if(val=='Enter City...') return null; // ignore if default text is in searchbox
			var name = $(this).attr("name"); // ignore location keyword if searching by map
			if(name=='keywordSearch' && val=='patio, sauna, etc') {} // grey textfield fill
			else if(name=='minYear' && val=='year') {} // grey textfield fill
			else if(name=='maxYear' && val=='year') {} // grey textfield fill
			else if(name=='cityZipSubdivision' && val=='City, Subdivision, ZIP') {} // grey textfield fill
			else if(name!='keyword' || $("select[name=searchBy]").val()=='location') query += "&" +name +"=" +val;
		}
	});
	
	$("input[type=hidden]").each(function () { /** hidden input **/
		var val = $(this).attr("value");
		if(val!="") {
			var name = $(this).attr("name");
			query += "&" +name +"=" +val;
		}
	});
	//alert(query);
	query += negativeStyles; /** add negative styles **/

	$.ajax({
   		type: "POST",
   		url: "/includes/ajax/search.php",
		dataType:"xmlDocument",
   		data: query,
   		success: function(xml){
			xml = parseXML(xml);
			displayResult(xml);
			//var ww = $('.thumbFrame:first').css('width');
			var w = $('.thumbFrame:first').width();
			var h = $('.thumbFrame:first').height();
/*			var w = 162;
			var h = 127;*/
			//$("#searchResults").css("display","none");
			$('.thumbnail').each(function () {
				$(this).load(function() {

					thumbv2($(this),w,h);
				});
			});
			$("#searchResults").load(function() {
				//($this).css("display","inline");
			});
		}
	});
}

/** Delay to wait till user stops typing **/
var delay = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();

/** typein Match AJAX function 
	gets called on every keypress in a textbox 
	need a div under an input box for this to work **/
function typeIn(field, value, propertyType) {
	query = "&field=" +field+"&value="+value+"&propertyType=" +propertyType;
	//alert(query);
	
	$.ajax({
   		type: "POST",
   		url: "/includes/ajax/typein.php",
		dataType:"xmlDocument",
   		data: "&field=" +field+"&value="+value+"&propertyType=" +propertyType,
   		success: function(xml){
			xml = parseXML(xml);
			//alert("RESULT: " +xml);
			var html = "<ul>";
			$('aResult',xml).each(function() {
				var text = $(this).text();
				html += "<li>" +text+ "</li>";
			});
			html += "</ul>";
			$("#subdivision_autocomplete").empty();
			$("#subdivision_autocomplete").append(html);
			$("#subdivision_autocomplete").css("display","block");
			
			$("#subdivision_autocomplete").find("li").mouseover( function() {
				$(this).attr("class","autocomplete_highlight");
			});
			$("#subdivision_autocomplete").find("li").mouseout( function() {
				$(this).attr("class","");
			});
			$("#subdivision_autocomplete").find("li").click( function() {
				$("input[name="+field+"]").attr("value",$(this).text());
				$("#subdivision_autocomplete").css("display","none");
			});
		}
	});


}

/** Display filters applied to search result **/
function getFiltersString() {
	var result = "";
	var keyword = $("input[name=keyword]").attr("value");
	var minPrice = $("select[name=minPrice]").val();
	var stories = $("select[name=stories_desc]").val();
	var numPics = $('select[name=minPics]').val();
	var pool = $('select[name=pool_desc]').is(':checked');
	
	var styles = ''; 
	var c = 0;
	$("input[name='styles[]']:checked").each(
    	function() { 
        	if (this.checked) {
				if(c>0) styles +=", ";
				styles += this.value;
				c++;
			}
		}
    ); 
	
	if(keyword) result += keyword +" real estate - ";
	if(minPrice>0) result += " price: $" +minPrice +" or more - ";
	if(stories!="") result += "stories: " +stories +" - ";
	if(styles!="") result += "styles: " +styles +" - ";
	if(numPics>0) result += "at least " +numPics +" pictures - ";
	if(pool) result += "has a pool - ";
	
	return result;
}

function displayResult(xml) {
	clearMarkers();// clear map overlays
	
	var sortUI = $("#sortUI");
//	resultsDiv.empty();
	$(".resultsIndex").empty();
	$("#resultSet").empty();
	
	/*** TEMPORARY HACK ****/
	/*** Redraw DIV content ***/
	
/*	html = "<input type='hidden' value='0' name='limitStart'/>";
	html += "<div class='resultsIndexBlock'><div class='resultsIndex'></div></div>";
	html += "<div id='resultSet'></div>";
	html += "<div class='resultsIndex'></div>";
	html += "<div id='tos'></div>";
	
	$("#searchResults").append(html);*/

	/**** END TEMPORARY HACK ****/
	var html = "";
	var resultsPerPage = parseInt($("resultsPerPage",xml).text());
	
	var thisPage = parseInt($("limitStart",xml).text())+1;

	var prev = thisPage - 1;
	var next = thisPage + 1;
	
	var maxPages = $("pages", xml).text();
	var lastItem = ((thisPage-1)*resultsPerPage)+resultsPerPage;
	var maxResults = $("resultsCount",xml).text();
	
	if(lastItem>maxResults) lastItem = maxResults;
	
	/** index block HTML **/
	
	html_indexBlock = ""; 

	if(sortUI.length==0) { 
		html_indexBlock += "<div id='sortUI'>";
		html_indexBlock += "<label>Sort By</label>";
		html_indexBlock += "<select name='sortOrder'>";
		html_indexBlock += "<option value='listing_price DESC' selected='selected'>Price (high to low)&nbsp;&nbsp;</option>";
		html_indexBlock += "<option value='listing_price ASC'>Price (low to high)</option>";
		html_indexBlock += "<option value='last_modified_date_time DESC'>Newest</option>";
		html_indexBlock += "<option value='pictures_number_of DESC'>Number of Pictures</option>";
		html_indexBlock += "<option value='Relevance DESC'>Best Match</option>";
		html_indexBlock += "<option value='bedrooms DESC'>Bedrooms</option>";
		html_indexBlock += "<option value='apx_sqft_primary_res DESC'>Square Feet</option>";
		html_indexBlock += "<option value='bathrooms_full DESC'>Baths</option>";
		html_indexBlock += "<option value='full_address ASC'>Address</option>";
		html_indexBlock += "</select>";
		html_indexBlock += "</div>";
	}
	
	$(".resultsIndexBlock").append(html_indexBlock);
	/** end index block html **/
	
	$("input[name=limitStart]").val($("limitStart",xml).text());
	$("input[name=maxPages]").val($("pages",xml).text());
	
	/** Filter string ***/
	//html += "<h4>" +getFiltersString()+ "</h4><br>"; 
	
	var count = 0;
	var row = 0;
	
	bounds = new GLatLngBounds();
	if(firstLoad==true) { map = new GMap2(document.getElementById("map_canvas")); }
	
	html_resultSet = "";
	
	$('aResult',xml).each(function() {
		var pid = $(this).find("mlNumber").text();
		var sqft = $(this).find("sqft").text();
		var picURL = "http://mlsmedia.metrolistmls.com/bigphoto/" +$(this).find("photoURL").text()+".jpg";
		var picNum = $(this).find("picNum").text();
		if(picNum==0) picURL = "/images/nopropimage.gif";
		var lng = $(this).find("geocodes").attr("lng");
		var lat = $(this).find("geocodes").attr("lat");
		
		if(lat!=0) {
			
			var data = new Array();
			data['mls_number'] = pid;
			data['address'] = $(this).find("address").text();
			data['price'] = $(this).find("price").text();
			data['bedrooms'] = $(this).find("bedrooms").text();
			data['bathrooms'] = $(this).find("bathrooms").text();
			data['sqft'] = sqft;
			data['city'] = $(this).find("city").text();
			data['picNum'] = $(this).find("picNum").text();
			data['picURL'] = picURL;
			data['lat'] = lat;
			data['lng'] = lng;
			data['listingOffice'] = $(this).find("listingOffice").text();
			
			loadPropertyMarker(lat,lng, data);
			bounds.extend(new GLatLng(lat, lng));
		}
		
		var propertyURL = '/idx/' + pid+'/';
		html_resultSet += "<div class='searchResult'>";
		html_resultSet += "<a href='" +propertyURL+"'>";
		html_resultSet += "<span class='thumbFrame'><img class='thumbnail' alt='property image' src='" +picURL+ "'><span class='thumbShadow'></span><span class='metrolistLogo'></span></span></a>";
		
		html_resultSet += "<p>";
		
		html_resultSet += "<a class='resultItemDetails' href='" + propertyURL+"'>";
		html_resultSet += "<span class='listingPrice'>" +$(this).find("price").text() +"</span>";
		html_resultSet += "<span class='address'>" +$(this).find("address").text() +"</span>";
		html_resultSet += "</a><br />";
		html_resultSet += "<span class='houseDetails'>" +$(this).find("bedrooms").text() +" br "+$(this).find("bathrooms").text() +" ba ";
		if(sqft!="na") html_resultSet += sqft +" sqft";
		html_resultSet += "<br/>";
		html_resultSet += $(this).find("city").text() +"<span class='camera'></span>" +$(this).find("picNum").text()+ "</span>";
		var office = $(this).find("listingOffice").text();
		office = office.replace("[.,]","");
		html_resultSet += "<div class='listingOffice'>" +$(this).find("listingOffice").text() +"</div>";
		html_resultSet += "</p>";
		
		html_resultSet += "</div>";
		
		count++;
		if(count>3) {
			count = 0;
			row++;
			if(row<4) html_resultSet += "<hr>";
		}
		
	});
	
	$("#resultSet").append(html_resultSet);
	/** End Result Set **/
	
	adjustLineHeight();
	// calculate map position

	if(firstLoad==true) {
		firstLoad=false;
		searchMap(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
	}
	else if($("select[name=searchBy]").val()=="location") {
		var zoom = map.getBoundsZoomLevel(bounds);
		if(zoom==19) zoom=18;							// avoid zoom level 19, since sometimes Google returns nothing
		map.setCenter(bounds.getCenter(), zoom);
	}

	html_bottomIndex = "";
	html_bottomIndex += "<span class='pageCount'>page <strong>" +thisPage +"</strong> of <strong>" +$("pages",xml).text() +"</strong></span>";
	html_bottomIndex += "<div class='resultsIndexButtns'>";
	if(prev>0) html_bottomIndex += "<input type='button' class='activeNav' name='prevSERP' id='prevSERP' value=''>";
	else html_bottomIndex += "<input type='button' class='inactiveNav' name='prevSERP' id='prevSERP' value=''>";
	
	if(next<=maxPages) html_bottomIndex += "<input type='button' class='activeNav' name='nextSERP' id='nextSERP' value=''>";
	else html_bottomIndex += "<input type='button' class='inactiveNav' name='nextSERP' id='nextSERP' value=''>";
	html_bottomIndex += "</div>";
	
	$(".resultsIndex").append(html_bottomIndex);
	/* TOS */
	
	var html_tos = "";
  	html_tos += "<hr>";
  	html_tos += "<p><span class='metrolistLogo metrolistBottom'></span>All measurements and all calculations of area (i.e., Sq Ft and Acreage) are approximate. Broker has represented to MetroList that Broker has a valid listing signed by seller authorizing placement in the MLS. Above information is provided by Seller and/or other sources and has not been verified by Broker. Copyright 2009 MetroList Services, Inc. <a href='/terms-of-use.php'>Terms of Use</a>. Last Updated March 4, 2010.</p>";
	
	if($("#tos").html()=="") $("#tos").append(html_tos);
	
	//resultsDiv.append(html);
	hideMsgBox();
	bindIndexButtons();
}

function showMsgBox() {
	$("#messageBox").css("display","block");
	var searchDivWidth = $("#searchResults").width();
	var msgWidth = $("#messageBox").width();
	var left = $("#searchResults").position().left + searchDivWidth/2 - msgWidth/2;
	var top = $("#searchResults").position().top;
	
	$("#messageBox").css("top",top+"px");
	$("#messageBox").css("left",left+"px");
}

function hideMsgBox() {
	$("#messageBox").css("display","none");
}

function parseXML(xml) {
	if (jQuery.browser.msie) {
		var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.loadXML(xml);
		xml = xmlDoc;
	}
	return xml;
}

negativeStyles = ""; // query string to store styles

$("select").change(function() { 
	$("input[name=limitStart]").attr("value",0);
	if($(this).attr("name")=='county') $("input[name=keyword]").attr("value",""); /** county search nulls searched for location **/
	submitSearch();
});

$("input[type=button]").click(function() { // input button clicks
									   //alert("imput cliked");
	$("input[name=limitStart]").attr("value",0); // reset search page number to 1
	if($(this).attr("name")=='disableStyles') { /* disable styles buttons */
		negativeStyles += "&negativeStyles[]=" +$(this).parent().find('input[name=styles[]]').attr("value");

		if($(this).parent().find('input[name=styles[]]').is(':checked')) {
			$(this).parent().find('input[name=styles[]]').attr("checked",false);
		}
		submitSearch();
		$(this).parent().remove();
	} 
	else if($(this).attr("name")=='addLocation') {
		var locList = $("#locationList");
		var li = document.createElement("li");
		locList.append(li); // add LI to UL
		
		var listItem = document.createElement("span");
		$(listItem).attr("class","locListItem");
		$(listItem).html($("input[name=cityZipSubdivision]").attr("value"));
		$(li).append(listItem); // add location value
		
		var clearButton = document.createElement("span");
		$(clearButton).attr("class","clearButton").text("[clear]");
		$(li).append(clearButton); // add clear button
		
		$(clearButton).click( function() {
			$(this).parent().remove();
			submitSearch();
		});
		
		$("input[name=cityZipSubdivision]").attr("value",""); // clear textbox
		submitSearch();
	}
	else submitSearch();
});

/** Adjust listing office css line height **/
function adjustLineHeight() {
	//alert("called!");
	$("span[class=listingOffice]").each( function() {
		//var height = $(this).attr("height");
		//alert("test");
	});
}

/** AUTOCOMPLETE **/
$("input[name=subdivision]").keyup(function() { 
	if($("input[name=subdivision]").attr("value").length<3) return null; // don't autocomplete unless at least 3 chars typed
	delay(function(){
	    if($("input[name=subdivision]").attr("value")=="") {
			$("#subdivision_autocomplete").css("display","none");
			return null;
		}
    	typeIn($("input[name=subdivision]").attr("name"), $("input[name=subdivision]").attr("value"), $("select[name=propertyType]").val());
    }, 1000 );
});

$('input[type=text]').bind('keypress', function(e) {
        if(e.keyCode==13){
               //alert("enter pressed!");
        }
});





$("input").change(function() {
	if($(this).attr("name")=="subdivision" || $(this).attr("name")=="cityZipSubdivision") return null; // don't process autocomplete
	$("input[name=limitStart]").attr("value",0);
	submitSearch();
});

/** this has to be refreshed on every submit because the bind is lost when DOM is destroyed **/
function bindIndexButtons() {
	$("input[name=prevSERP]").each(function() {
		$(this).click(function() {
			if($(this).attr("class")=="activeNav") {
				var page = parseInt($("input[name=limitStart]").attr("value"))-1;
				$("input[name=limitStart]").attr("value",page);
				//alert(page);
				submitSearch();
				window.scrollTo(0,0);
			}
		});
	});
	$("input[name=nextSERP]").click(function() {
		if($(this).attr("class")=="activeNav") {
			var page = parseInt($("input[name=limitStart]").attr("value"))+1;
			$("input[name=limitStart]").attr("value",page);
			//alert(page);
			submitSearch();
			window.scrollTo(0,0);
		}
	});
	/** Bind sort order UI **/
	$("select[name=sortOrder]").change(function() {
		submitSearch();
	});
}

bindIndexButtons(); /** bind on page load **/

$("span[id=clearKeywordsButton]").click(function() {
	$("input[name=keywordSearch]").attr("value","");
	submitSearch();
});

