var ds = 'ms_search_shorew';
var max_results = "250";
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', 'wf');

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

	if (document.getElementById('lp_c4v43c').checked) {
		retVal += "&lp_c4v43c=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 wf = document.getElementById('wf').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;

	w += " AND lp_c2v2c = 'N' ";

	if (p_type.length > 0) {
                w += " AND lp_c4v46c = '" + escape(p_type) + "'";
        }
        if (wf.length > 0) {
                w += " AND lp_fg_WaterAccess = '" + wf + "'";
        }
	if (document.getElementById('lp_c4v43c').checked) {
		w += " AND lp_c4v43c = 'Y'";
	}
	if (document.getElementById('lp_ind_OpenHouse').checked) {
		w += " AND lp_ind_OpenHouse = '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();


        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_ds_OpenHouseDay,lp_ind_OpenHouse,lp_ds_OpenHouseTime,lp_ListingCity,Comments,cd_Office,TO_DAYS(NOW()) - TO_DAYS(lp_Listing_Date) AS DOM, DATE_FORMAT(lp_dt_last_updated, '%25a %25m%2f%25d%2f%25Y') AS lp_dt_last_updated,lp_detailURL";

	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 + '&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("PROPERTY");
	var offices = xmlDoc.getElementsByTagName("OFFICE");
	var pois = xmlDoc.getElementsByTagName("POI");


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

        if (props.length > 0) {
                document.getElementById('propcount').innerHTML = '<b>Found ' + xmlDoc.getElementsByTagName("PROPERTIES").item(0).getAttribute("count") + ' Listings:</b> Click the home icon for more information on each or <a href="javascript: document.form2.submit()">view results as list</a>.';
		createSummary(props);
        } else {                
		document.getElementById('propcount').innerHTML = '<b>Found ' + xmlDoc.getElementsByTagName("PROPERTIES").item(0).getAttribute("count") + ' Listings:</b> Icons will appear when the listing count is under ' + max_results;
		clearSummary();

        }

        if (props.length > 0) {
                document.getElementById('poi_div').style.visibility = 'visible';
        } else {
                document.getElementById('poi_div').style.visibility = 'hidden';
                document.getElementById('POI_SCHOOL').checked = false;
        }

	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_DFLT_PHOTO_URL').length > 0) {
                        photo_string = '<a href="http://www.shorewest.com/vp/AgentServlet?cd_Company=SHOREW&SITE=SHOREW&Search=true&ScreenID=AgentsSummary_Public&cd_Office=' + cleanString(offices[i].getAttribute('O_CD_OFFICE')) + '&ScreenID_Cur=OFFICE_SEARCH" target="_parent"><img src="http://www.redata.com/100021/Shorew/graphics/companylogo.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:13px;"></a></div>';
		balloon += photo_string;
		balloon += '<div class="address">' + cleanString(offices[i].getAttribute('O_NM_OFFICE')) + '</div>';
		balloon += cleanString(offices[i].getAttribute('O_ADDRESS_01')) + '<br />';
		balloon += '<a href="http://www.shorewest.com/vp/AgentServlet?cd_Company=SHOREW&SITE=SHOREW&Search=true&ScreenID=AgentsSummary_Public&cd_Office=' + cleanString(offices[i].getAttribute('O_CD_OFFICE')) + '&ScreenID_Cur=OFFICE_SEARCH" 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="http://www.redata.com/100021/Shorew/graphics/companylogo.jpg" width="16" height="16" border="0">';
                area.style.left=x1 + 'px';
                area.style.top=y1 + 'px';
                area.style.position='absolute';
                area.style.zIndex=1;
                area.onmouseover = function() {
			if (!dragging) {
				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:13px;"></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() {
			if (!dragging) {
	                        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) {
			if (pres_agent.length > 0) {
	    			photo_string = '<a href="' + root_url + '/vp/ListingServlet?cd_MLS=' + props[i].getAttribute('cd_MLS') + '&SITE=' + site + '&ScreenID=AGENT_LISTING_DETAIL&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>';
			} else {
	    			photo_string = '<a href="' + root_url + '/homes/' + props[i].getAttribute('lp_detailURL') + '?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 += '<table width="150" cellspacing="0" cellpadding="0"><tr>';
		if (props[i].getAttribute('lp_ind_OpenHouse') == 'Y') {
			balloon += '<td colspan="2" align="right"><a href="javascript:hideAll();"><img src="images/close_icon.gif" style="width:10px" border="0"></a></td></tr><td align="left"><img src="images/icon_openhouse.gif" style="width:20px"></td><td align="right" valign="bottom">' + cleanString(props[i].getAttribute('lp_ds_OpenHouseDay')) + ' ' + cleanString(props[i].getAttribute('lp_ds_OpenHouseTime')) + '</td>';
		} else {
	                balloon += '<td align="right"><a href="#" onClick="hideAll();"><img border="0" src="images/close_icon.gif" style="width:10px"></a></td>';
		}
 
		balloon += '</tr></table>';

		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>';

		if (pres_agent.length > 0) {
			balloon += '<a href="' + root_url + '/vp/ListingServlet?cd_MLS=' + props[i].getAttribute('cd_MLS') + '&SITE=' + site + '&ScreenID=AGENT_LISTING_DETAIL&pres_agent=' + pres_agent + '&mapvars=' + queryString + '%26s_layer%3D' + props[i].getAttribute('cd_MLS') + '" target="_parent">More Details</a>';
		} else {
			balloon += '<a href="' + root_url + '/homes/' + props[i].getAttribute('lp_detailURL') + '?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 < 100) {
                        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() {
			if (!dragging) {
				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");
	var saveSearch = getElmById('saveSearch');
	
	if (props.length > 0) 
	{

		var cd_MLS_sum = 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_sum.value = props_list;
		numFound.value = props.length;

		saveSearch.innerHTML = createSaveLink();
		saveSearch.style.visibility = 'visible';

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

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

function createSaveLink()
{
        var link = "";

        if (cookieid.length > 0)
        {
                link = '<a href="javascript:postSaveSearch()">Save This Search</a>';
        }
        else
        {
		link = 'Use myShorewest 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 + '&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 wf = document.getElementById('wf').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 (p_type.length > 0) {
                c += "Property Type equals " + p_type + "<BR>";
        }

        if (wf.length > 0) {
                c += "Water frontage/access equals " + wf + "<BR>";
        }
	
	if (document.getElementById('lp_c4v43c').checked) {
		c += " Farm 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>';
                        }
                }
        }
}

function compareProperties() {
	var inputs = document.getElementsByTagName("input");

	var list = "";

	for (var i = 0; i < inputs.length; i++) {

		if (inputs[i].id == 'compare_prop') {
			if (inputs[i].checked) {
				if (list.length == 0) {
					list = inputs[i].value;
				} else {
					list += ',' + inputs[i].value;
				}
			}
		}
	}

	if (list.length > 0) {
		 var w = window.open('http://mapping.redata.com/mapping_v2006/jsps/' + site + '/tv_us/viewer.jsp?&cd_MLS=' + list + '&MS_CONTEXT=DC_LISTING_SUMMARY_MAP&sortCriteria=cd_MLS&NO_CACHE=true', 'MyWindow', 'toolbar=yes,location=yes,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=yes,width=950,height=625,left=20,top=20');

	} else {
		alert('You must select at least 1 property to compare.');
	}
        
	return true;
		
}

