var ds = 'ms_search_reo';
var max_results = "500";
var open_div = "";

function getMap(envelope) {

        if (okToSend) {
	
	        http = getHTTPObject();

	        if ((http != null) ) {
        		okToSend = false;
		        var axl = "";
		        axl = getTiledMapRequest("");
		        http.open("POST", cache_url, true);
		        http.onreadystatechange = printTiledResponse;
		        http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		        showLayer('loading');
		        http.send(axl);
        	}
        }
}

function createQueryString()
{
	var retVal = "minx=" + minx + "&miny=" + miny + "&maxx=" + maxx + "&maxy=" + maxy;

	var myvars = new Array('lp_low', 'lp_high', 'beds_low', 'baths_low', 'p_type', 'lp_yr_Struct_Built', 'lp_no_Acres_Total', 'lp_amt_Struct_SqFt_Est');

        if (cd_MLS_sum.length > 0) {
                retVal = "cd_MLS_sum=" + cd_MLS_sum + "&delay_map=y";
        }


	for (var i = 0; i < myvars.length; i++) {
		retVal = retVal + "&" + myvars[i] + "=" + getElmById(myvars[i]).value;
	}

	if (document.getElementById('basement').checked) {
		retVal += "&basement=true";
	}
	if (document.getElementById('garage').checked) {
		retVal += "&garage=true";
	}
	if (document.getElementById('foreclosure').checked) {
		retVal += "&foreclosure=true";
	}
	if (document.getElementById('rental').checked) {
		retVal += "&rental=true";
	}

	retVal += "&zoom=true&scale=" + scale;

	return escape(retVal);
}


function buildWhere() 
{
       	var lp_low = document.getElementById('lp_low').value;
        var lp_high = document.getElementById('lp_high').value;
        var beds_low = document.getElementById('beds_low').value;
        var baths_low = document.getElementById('baths_low').value;        
	var p_type = document.getElementById('p_type').value;        
	var lp_yr_Struct_Built = document.getElementById('lp_yr_Struct_Built').value;
	var lp_no_Acres_Total = document.getElementById('lp_no_Acres_Total').value;
	var lp_amt_Struct_SqFt_Est = document.getElementById('lp_amt_Struct_SqFt_Est').value;

	var w = ' AND lp_Listing_Price >= ' + lp_low + ' AND lp_Listing_Price <= ' + lp_high + ' AND lp_No_Bedrooms >= ' + beds_low + '  AND lp_No_Bathrooms >= ' + baths_low;

	if (p_type.length > 0) {
                w += " AND lp_tp_Improvement = '" + escape(p_type) + "'";
        }

	if (cd_MLS_sum.length > 0) {
		w += " AND cd_MLS IN (" + cd_MLS_sum + ")";
	}
	
	if (lp_yr_Struct_Built.length > 0) {
		w += " AND lp_yr_Struct_Built >= " + lp_yr_Struct_Built;
	}
	if (lp_no_Acres_Total.length > 0) {
		w += " AND lp_no_Acres_Total >= " + lp_no_Acres_Total;
	}
	if (lp_amt_Struct_SqFt_Est.length > 0) {
		w += " AND lp_amt_Struct_SqFt_Est >= " + lp_amt_Struct_SqFt_Est;
	}
	if (document.getElementById('basement').checked) {
		w += " AND lp_c1v16c = 'Y'";
	}
	if (document.getElementById('garage').checked) {
		w += " AND lp_c1v17c = 'Y'";
	}
	if (document.getElementById('foreclosure').checked) {
		w += " AND lp_c1v14c = 'Y'";
	}
	if (document.getElementById('rental').checked) {
		w += " AND lp_c1v13c = 'Y'";
	}
	return w;
}

function buildPoiWhere() {
        var w = "";
        var cats = "";

        var inputs = document.getElementsByTagName('input');

        for(var i=0; i<inputs.length; i++){
                var type = inputs[i].type;
                var id = inputs[i].id;
                var name = inputs[i].name;
                if (type == 'checkbox' && id.indexOf('POI_') == 0) {
                        if (inputs[i].checked) {
                                if (cats.length == 0) {
                                        cats += "'" + name + "'";
                                } else {
                                        cats += ",'" + name + "'";
                                }
                        }
                }
        }

        if (cats.length > 0) {
                w = " AND tp_category IN (" + cats + ")";
        }

        return w;
}

function getTiledMapRequest(env)
{       

	var w = buildWhere();
        var w_poi = buildPoiWhere();

	if (w_poi.length > 0) {
		w_poi += " ORDER BY RAND() LIMIT 250 ";
	}

        w += " ORDER BY " + order_by + " " + up_down;

   var fl = 'cd_MLS,lp_MLS_Number,FORMAT(lp_Listing_Price, 0) as lp_Listing_Price_Display,lp_Listing_Price,lp_ListingAddr1,lp_No_Bedrooms,lp_No_Bathrooms,lp_res_Lat,lp_res_Long,lp_Photo_URL,lp_PhotoDesc_1,lp_ind_OpenHouse,cd_Office,TO_DAYS(NOW()) - TO_DAYS(lp_Listing_Date) AS DOM,Comments,ds_OpenHouseDay,ds_OpenHouseTime,lp_amt_Struct_SqFt_Est,lp_cd_Source,cd_Company,v15c';

	if (delay_map.length > 0) {
                scale = "";
        }

	var axl = 'SITE=' + site + '&INC_OFFICES=' + (getElmById('INC_OFFICES').checked ? "true" : "") + '&minx=' + minx + '&maxy=' + maxy + '&maxx=' + maxx + '&miny=' + miny + '&cache=' + cache + '&width=' + width + '&height=' + height + '&INC_LISTINGS=y&DS=' + ds +'&MAX_RESULTS=' + max_results + '&FL=' + fl + "&scale=" + scale + '&zoom=' + fixedzoom + "&CACHE_ORIGIN_X=" + cache_origin_x + "&CACHE_ORIGIN_Y=" + cache_origin_y + "&SRCH_WHERE=" + w + '&DELAY_MAP=' + delay_map + '&US_TILES=true' + "&INC_POI=" + (w_poi.length > 0 ? "true" : "") + "&POI_WHERE=" + w_poi;

        return axl;

}

function printTiledResponse(){

if (http.readyState == 4) {
    
	if (http.status == 200) {

      	isWorking = false;
      	
	var result = http.responseText;

	var xmlDoc = getXMLDoc();

	var tiles = xmlDoc.getElementsByTagName("TILES")[0].getElementsByTagName("TILE");
	scale = xmlDoc.getElementsByTagName("TILES").item(0).getAttribute("scale");
	resolution = xmlDoc.getElementsByTagName("TILES").item(0).getAttribute("resolution");

	positionMileSlider();

	var env = xmlDoc.getElementsByTagName("ENVELOPE").item(0);

	minx = parseFloat(env.getAttribute("minx"));
	miny = parseFloat(env.getAttribute("miny"));
	maxx = parseFloat(env.getAttribute("maxx"));
	maxy = parseFloat(env.getAttribute("maxy"));

	clearImageMap();

	placeTiles(tiles);

	fixedzoom = "";
	
	var props = xmlDoc.getElementsByTagName("RESPONSE")[0].getElementsByTagName("PROPERTY");
	var offices = xmlDoc.getElementsByTagName("RESPONSE")[0].getElementsByTagName("OFFICE");
	var pois = xmlDoc.getElementsByTagName("RESPONSE")[0].getElementsByTagName("POI");

	if (cd_MLS_sum.length > 0 && props.length == 0) {
		alert("None of the properties from your summary have geocodes. Please use your browsers back button to return to list view.");
	}

	processPropertyRecs(props);
	processOfficeRecs(offices);
	processPoiRecs(pois);

	if (props.length == 0) {
        	document.getElementById('properties_found').innerHTML = '<img src="images/map_pfound_tleft.gif" /><p>Properties Found: ' + xmlDoc.getElementsByTagName("PROPERTIES").item(0).getAttribute("count") + '. Please refine your search.</p><img src="images/map_pfound_tright.gif" />';
                clearSummary();
        } else {
        	document.getElementById('properties_found').innerHTML = '<img src="images/map_pfound_tleft.gif" /><p><a href="javascript:document.form2.submit()">Properties Found: ' + xmlDoc.getElementsByTagName("PROPERTIES").item(0).getAttribute("count") + '.Click here to see all results.</a></p><img src="images/map_pfound_tright.gif" />';
                createSummary(props);

        }

	if (delay_map.length > 0) {
                delay_map = "";
      	}

	hideLayer('loading');
    }
 
   okToSend = true;
  } 
}

function processOfficeRecs(offices)
{

	for (var i = 0; i < offices.length; i++) 
	{
		var x = parseInt(offices[i].getAttribute('x'));
		var y = parseInt(offices[i].getAttribute('y'));
  	
		var x1 = x;
                var y1 = y;

		var icon_type = "";

                if (x > (width / 2)) {
                	if (y > (height / 2)) {
				icon_type = "BR";
				x = x - icon_w;
				y = y - icon_h; 
			} else {
				icon_type = "TR";
				x = x - icon_w + 6;
				y = y + 4;
			}				
		} else {
                	if (y > (height / 2)) {
				icon_type = "BL";
				y = y - icon_h;
				x = x + 5;
			} else {
				icon_type = "TL";
				x = x + 5;
				y = y + 3;
			}
                }

                var myDiv = document.createElement('DIV');
                myDiv.id = "OFFICE_" + i;
                myDiv.style.position='absolute';
                myDiv.style.visibility='hidden';
                myDiv.style.left =x + 'px';
                myDiv.style.top = y + 'px';
                myDiv.style.width = icon_w + 'px';
                myDiv.style.height= icon_h + 'px';
                myDiv.style.zIndex=2;

                var photo_string = "";

                if (offices[i].getAttribute('O_PHOTO_URL').length > 0) {
                     photo_string = '<img src="' + cleanString(offices[i].getAttribute('O_PHOTO_URL')) + '" width="150" height="117" border="0"></a>';       
                }

                var balloon = '<div class="balloon_' + icon_type + '">';
                balloon += '<div class="inner_balloon">';
                balloon += '<div class="close_icon"><a href="javascript:hideAll();"><img border="0" src="images/close_icon.gif" style="width:17px;"></a></div>';
                balloon += photo_string;
                balloon += '<div class="address">' + cleanString(offices[i].getAttribute('O_NM_OFFICE')) + '</div>';
                balloon += cleanString(offices[i].getAttribute('O_TELEPHONE1')) + '<br />';

                balloon += '<font size="-2"><a href="mailto:' + cleanString(offices[i].getAttribute('O_EMAIL')) + '">' + cleanString(offices[i].getAttribute('O_EMAIL')) + '</a></font><br />';
		 balloon += '<a href="' + root_url + '/vp/AgentServlet?ScreenID=OFFICE_DETAIL_P&SITE=REO&A_CD_COMPANY=REO&context=DC_OFFICE_DETAIL_VIEW&cd_Office=' + cleanString(offices[i].getAttribute('O_CD_OFFICE')) + '" target="_parent">More Details</a>';

                balloon += '</div>';
                balloon += '</div>';
                balloon += '</div>';

		myDiv.innerHTML = balloon;

                mapContainer.appendChild(myDiv);

                        
                var area = document.createElement('DIV');
                area.id = i;
                area.innerHTML = '<img src="images/logo_small.gif" border="0">';
                area.style.left=x1 + 'px';
                area.style.top=y1 + 'px';
                area.style.position='absolute';
                area.style.zIndex=1;
                area.onmouseover = function() {
			hideAll()
                        document.getElementById('OFFICE_' + this.id).style.visibility = 'visible';
			open_div = document.getElementById('OFFICE_' + this.id);
                        document.onmousemove = checkPosition;

                }
                
                mapContainer.appendChild(area); 
                
        }       
}

function processPoiRecs(props)
{

        for (var i = 0; i < props.length; i++) {
                var x = parseInt(props[i].getAttribute('x'));
                var y = parseInt(props[i].getAttribute('y'));

                var x1 = x;
                var y1 = y;

                var icon_type = "";

                if (x > (width / 2)) {
                        if (y > (height / 2)) {
                                icon_type = "BR";
                                x = x - icon_w;
                                y = y - icon_h;
                        } else {
                                icon_type = "TR";
                                x = x - icon_w + 6;
                                y = y + 4;
                        }
                } else {
                        if (y > (height / 2)) {
                                icon_type = "BL";
                                y = y - icon_h;
                                x = x + 5;
                        } else {
                                icon_type = "TL";
                                x = x + 5;
                                y = y + 3;
                        }
                }

                var cd_key = cleanString(props[i].getAttribute('cd_key'));

                var myDiv = document.createElement('DIV');
                myDiv.id = "POI_" + cd_key;
                myDiv.style.position='absolute';
                myDiv.style.visibility='hidden';
                myDiv.style.left =x + 'px';
                myDiv.style.top = y + 'px';
		myDiv.style.width = icon_w + 'px';
                myDiv.style.height= icon_h + 'px';
                myDiv.style.zIndex=2;

                var tmp_balloon = '<div class="balloon_' + icon_type + '">';
                tmp_balloon += '<div class="inner_balloon_poi">';

                tmp_balloon += '<div class="close_icon"><br><a href="javascript:hideAll();"><img border="0" src="images/close_icon.gif" style="width:17px;"></a></div><br>';

                if (cleanString(props[i].getAttribute('ds_display')).length > 0) {
                        tmp_balloon += '<table><tr><td align="left">' + cleanString(props[i].getAttribute('ds_display')) + '</td></tr></table>';
                }

                tmp_balloon += '</div>';

                tmp_balloon += '</div>';

                myDiv.innerHTML = tmp_balloon;

                mapContainer.appendChild(myDiv);

                var area = document.createElement('DIV');
                area.id = cd_key;

		area.innerHTML = '<img src="images/' + cleanString(props[i].getAttribute('ds_icon')) + '" border="0">';

                area.style.left=x1 + 'px';
                area.style.top=y1 + 'px';
                area.style.position='absolute';
                area.style.zIndex=1;
                area.onmouseover = function() {
                        hideAll();
                        document.getElementById('POI_' + this.id).style.visibility = 'visible';
			open_div = document.getElementById('POI_' + this.id);
                        document.onmousemove = checkPosition;
                }

                mapContainer.appendChild(area);

        }
}
	
function processPropertyRecs(props)
{


	var props_list = "";

	var queryString = createQueryString();

	for (var i = 0; i < props.length; i++) {
		var x = parseInt(props[i].getAttribute('x'));
		var y = parseInt(props[i].getAttribute('y'));
	
		if (props_list.length == 0) {
			props_list = props[i].getAttribute("cd_MLS");
		} else {
			props_list = props_list +  "," + props[i].getAttribute("cd_MLS");
		}
	
		var x1 = x;
		var y1 = y;

                var icon_type = "";

                if (x > (width / 2)) {
                        if (y > (height / 2)) {
                                icon_type = "BR";
                                x = x - icon_w;
                                y = y - icon_h;
                        } else {
                                icon_type = "TR";
                                x = x - icon_w + 6;
                                y = y + 4;
                        }
                } else {
                        if (y > (height / 2)) {
                                icon_type = "BL";
                                y = y - icon_h;
                                x = x + 5;
                        } else {
                                icon_type = "TL";
                                x = x + 5;
                                y = y + 3;
                        }
                }

		var myDiv = document.createElement('DIV');
		myDiv.id = "LISTING_" + i;
		myDiv.style.position='absolute';
		myDiv.style.visibility='hidden';
 		if (s_layer == props[i].getAttribute('cd_MLS')) {
                        myDiv.style.visibility = 'visible';
                        s_layer = '';
                }
		myDiv.style.left =x + 'px';
		myDiv.style.top = y + 'px';
		myDiv.style.width = icon_w + 'px';
		myDiv.style.height= icon_h + 'px';
		myDiv.style.zIndex=2;

		var photo_string = "";

		if (props[i].getAttribute('lp_Photo_URL').length > 0) {
    			photo_string = '<a href="' + root_url + '/vp/ListingServlet?cd_MLS=' + props[i].getAttribute('cd_MLS') + '&SITE=' + site + '&ScreenID=LISTING_DETAIL_P_BLANK&pres_agent=' + pres_agent + '&mapvars=' + queryString + '%26s_layer%3d' + props[i].getAttribute('cd_MLS') + '" target="_parent"><img src="http://' + cleanString(props[i].getAttribute('lp_Photo_URL')) + props[i].getAttribute('lp_MLS_Number') + 'at.jpg" width="150" height="117" border="0"></a>';
		}	

                var balloon = '<div class="balloon_' + icon_type + '">';
                balloon += '<div class="inner_balloon">';
                balloon += '<div class="close_icon"><a href="javascript:hideAll();"><img border="0" src="images/close_icon.gif" style="width:17px;"></a></div>'; 
		balloon += photo_string;
                balloon += '<div class="address">' + cleanString(props[i].getAttribute('lp_ListingAddr1')) + '</div>';
                balloon += '$' + cleanString(props[i].getAttribute('lp_Listing_Price_Display')) + '<br />';
		balloon += props[i].getAttribute('lp_No_Bedrooms') + ' Beds ' + props[i].getAttribute('lp_No_Bathrooms') + ' Baths<br>';

		balloon += '<a href="' + root_url + '/vp/ListingServlet?cd_MLS=' + props[i].getAttribute('cd_MLS') + '&SITE=' + site + '&ScreenID=LISTING_DETAIL_P_BLANK&pres_agent=' + pres_agent + '&mapvars=' + queryString + '%26s_layer%3D' + props[i].getAttribute('cd_MLS') + '" target="_parent">More Details</a>';

                balloon += '</div>';
                balloon += '</div>';
                balloon += '</div>';

                myDiv.innerHTML = balloon;

		mapContainer.appendChild(myDiv);
	
		var area = document.createElement('DIV');
		area.id = i;
		if (props.length < 250) {
			if (props[i].getAttribute('DOM') < 8) { 
				area.innerHTML = '<img src="images/icon_map_newlisting.png" border="0">';
			} else if (props[i].getAttribute('lp_ind_OpenHouse') == 'Y') {
				area.innerHTML = '<img src="images/icon_map_openhouse.png" border="0">';
			} else {
				area.innerHTML = '<img src="images/icon_map_active.png" border="0">';
			}
		} else {
			if (props[i].getAttribute('DOM') < 8) {
                        	area.innerHTML = '<img src="images/icon_map_newlisting.png" border="0" width="13" height="13">';
                        } else if (props[i].getAttribute('lp_ind_OpenHouse') == 'Y') {
                        	area.innerHTML = '<img src="images/icon_map_openhouse.png" border="0" width="13" height="13">';
                        } else {
                        	area.innerHTML = '<img src="images/icon_map_active.png" border="0" width="13" height="13">';
                        }
                }

		area.style.left=x1 + 'px';
		area.style.top=y1 + 'px';
		area.style.position='absolute';
		area.style.zIndex=1;
		area.onmouseover = function() {
			hideAll(); 
			document.getElementById('LISTING_' + this.id).style.visibility = 'visible';
			open_div = document.getElementById('LISTING_' + this.id);
                        document.onmousemove = checkPosition;
 
		}

		mapContainer.appendChild(area);
	
	}

	var theform = getElmById("theForm");
	
	if (props.length > 0) 
	{

		var cd_MLS = getElmById("cd_MLS_sum");
		var numPages = getElmById("numPages");
		var numFound = getElmById("numFound");
		var searchCriteria = getElmById("searchCriteria");
		var mapvars = getElmById("mapvars");
	
		mapvars.value = unescape(createQueryString());
		theform.style.visibility = 'visible';
		cd_MLS.value = props_list;
		numFound.value = props.length;

		if (props.length > 5) {
			numPages.value = Math.ceil(parseFloat(props.length / 5));
		} else {
			numPages.value = "1";
		}

	} else {
		theform.style.visibility = 'hidden';
	}
	
}

function createSaveLink()
{
        var link = "";

        if (cookieid.length > 0)
        {
                link = '<a href="javascript:postSaveSearch()">Save This Search</a>';
        }
        else
        {
		link = 'Use FirstToKnow login to save this search.';
        }

        return link;

}

function postSaveSearch()
{

        if (okToSend) {
                http = getHTTPObject();

                if ((http != null) ) {
                        showLayer('loading');
                        okToSend = false;
                        var dat = getSaveData();

                        http.open("POST", save_url, true);
                        http.onreadystatechange = saveResponse;
                        http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                        http.send(dat);
                        hideLayer('loading');
                }
        }

        okToSend = true;
}

function getSaveData()
{
        var dat = 'SITE=' + site + '&cd_Contact=' + cookieid + 'DAYS_TO_LIVE=180&sql=';

        var sql = "SELECT Listing.cd_MLS FROM ListingPublic,Listing WHERE ListingPublic.cd_MLS = Listing.cd_MLS AND " + buildWhere()  + ' AND lp_res_Lat > ' + miny + ' AND lp_res_Lat < ' + maxy + ' AND lp_res_Long > ' + minx + ' AND lp_res_Long < ' + maxx;

        dat += sql + '&criteria=' + buildCriteria() + '&fg_1=Y';

        return dat;
}

function buildCriteria()
{
 	var lp_low = document.getElementById('lp_low').value;
        var lp_high = document.getElementById('lp_high').value;
        var beds_low = document.getElementById('beds_low').value;
        var baths_low = document.getElementById('baths_low').value;
        var p_type = document.getElementById('p_type').value;
        var lp_yr_Struct_Built = document.getElementById('lp_yr_Struct_Built').value;
        var lp_no_Acres_Total = document.getElementById('lp_no_Acres_Total').value;
        var lp_amt_Struct_SqFt_Est = document.getElementById('lp_amt_Struct_SqFt_Est').value;

        var c = "Latitude greater than " + miny + " Latitude less than " + maxy + "<br>";

        c += "AND Longitude greater than " + minx + " Longitude less than " + maxx + "<br>";

        if (lp_low.length > 0) {
                c += "Listing Price greater than " + lp_low + "<BR>";
        }

        if (lp_high.length > 0) {
                c += "Listing Price less than " + lp_high + "<BR>";
        }

        if (beds_low.length > 0) {
                c += "Bedrooms greater than " + beds_low + "<BR>";
        }

        if (baths_low.length > 0) {
                c += "Bathrooms greater than " + baths_low + "<BR>";
        }
	if (lp_yr_Struct_Built.length > 0) {
		c += "Year Struct Built greater than " + lp_yr_Struct_Built + "<br>";
	}
	if (lp_no_Acres_Total.length > 0) {
		c += "Total Acres greater than " + lp_no_Acres_Total + "<br>";
	}
	if (lp_amt_Struct_SqFt_Est.length > 0) {
		c += "SqFt greater than " + lp_amt_Struct_SqFt_Est + "<br>";
	}
        if (p_type.length > 0) {
                c += "Property Type equals " + p_type + "<BR>";
        }

	if (document.getElementById('basement').checked) {
		c += "Basement equals Y<br>";
	}
	if (document.getElementById('garage').checked) {
		c += "Garage equals Y<br>";
	}
	if (document.getElementById('foreclosure').checked) {
		c += "Foreclosure equals Y<br>";
	}
	if (document.getElementById('rental').checked) {
		c += "Rental equals Y<br>";
	}

        return c;
}

function saveResponse() {

        if (http.readyState == 4) {
                if (http.status == 200) {
                        isWorking = false;

                        var result = http.responseText;
                        var xmlDoc = getXMLDoc();
                        var retVal = xmlDoc.getElementsByTagName("RESPONSE").item(0).getAttribute("returnCode");

                        var ss = getElmById("saveSearch");
                        if (retVal == 'true') {
                                ss.innerHTML = '<font color="red">Search Successfully Saved</font>';
                        } else {
                                ss.innerHTML = '<font color="red">There was a problem saving your search</font>';
                        }
                }
        }
}


