var ds = 'ms_search_firstweber';
var max_results = "300";
var open_div = "";
var s_layer = '';

function setJumpEnvelope(ix, iy, ax, ay, sc)
{
        minx = ix;
        miny = iy;
        maxx = ax;
        maxy = ay;

        fixedzoom = "true";
        scale = sc;

        getMap("");

}

function getMap(envelope) {

	if (okToSend) {
  	http = getHTTPObject();

  	if ((http != null) ) {
	okToSend = false;
    	var axl = getMapRequest(envelope);
   
    	http.open("POST", url, true);
    	http.onreadystatechange = printResponse;
    	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    	showLayer('loading');
    	http.send(axl);
	}
	} else {
		alert ("Waiting for previous response");
	}
}

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

	retVal += "&zoom=true&scale=" + scale;
	
	if (search_type == 'OH') {
		retVal += "&search_type=OH";
	}

	if (search_type == 'NL') { 
		retVal += "&search_type=NL";
	}

	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 + ' OR lp_Listing_Price_Low >= ' + lp_low + ') AND (lp_Listing_Price <= ' + lp_high + ' OR (lp_Listing_Price_Low <= ' + lp_high + ' AND lp_Listing_Price_Low > 0)) AND lp_No_Bedrooms >= ' + beds_low + '  AND lp_No_Bathrooms >= ' + baths_low;


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

        if (search_type == 'OH') {
                w += " AND lp_ind_OpenHouse = 'Y'";
        }

        if (search_type == 'NL') {
                w += " AND lp_Listing_Date > DATE_ADD(NOW(), INTERVAL -14 DAY)";
        }

	return w;
}

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>";
	}

	return c;
}

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 getMapRequest(env)
{
	var w = buildWhere();
	var w_poi = buildPoiWhere();

	if (w_poi.length > 0) {
		w_poi += " AND fg_active = 'Y'";
	}

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

	var fl = "cd_MLS,lp_MLS_Number,FORMAT(lp_Listing_Price, 0) as lp_Listing_Price,lp_ListingAddr1,lp_No_Bedrooms,lp_No_Bathrooms,lp_res_Lat,lp_res_Long,Photo_URL,PhotoDesc_1,lp_c4v43c,ds_OpenHouseDay,lp_ind_OpenHouse,ds_OpenHouseTime";

	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 + "&INC_POI=" + (w_poi.length > 0 ? "true" : "") + "&POI_WHERE=" + w_poi;

	axl += "&US_TILES=true";


	return axl;
}

function saveResponse() {
	
	if (http.readyState == 4) {
		if (http.status == 200) {
			isWorking = false;
        
		        	var result = http.responseText;
        			var xmlDoc;
        			if(document.implementation && document.implementation.createDocument) { 
					xmlDoc = document.implementation.createDocument("", "", null);
                			xmlDoc.async="false";
                			xmlDoc.loadXML(result);
			        } else if (window.ActiveXObject){
                			xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                			xmlDoc.async="false";
                			xmlDoc.loadXML(result);
        			}

			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 printResponse(){

if (http.readyState == 4) {
    if (http.status == 200) {

      	isWorking = false;
      
      	var result = http.responseText;

	var xmlDoc;
	
      	if(document.implementation && document.implementation.createDocument) { 
      		// MOZILLA 
       	 	xmlDoc = document.implementation.createDocument("", "", null);
      	 	xmlDoc.async="false";
         	xmlDoc.loadXML(result);
      	} else if (window.ActiveXObject){
      	 	//IE
      	  	xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
	  	xmlDoc.async="false";
	  	xmlDoc.loadXML(result);
       	}

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

        resolution = xmlDoc.getElementsByTagName("TILES").item(0).getAttribute("resolution");

        positionSlider();

	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 = "";

	document.getElementById('propcount').innerHTML = '<h2>Property Count: ' + xmlDoc.getElementsByTagName("PROPERTIES").item(0).getAttribute("count") + '</h2>';

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

	
	processPropertyRecs(props, xmlDoc.getElementsByTagName("PROPERTIES").item(0).getAttribute("count"));
	processOfficeRecs(offices);
	
	if (props.length > 0) {
		document.getElementById('poi_div').style.visibility = 'visible';
		processPoiRecs(pois);
		createSummary(props);
	} else {
		document.getElementById('poi_div').style.visibility = 'hidden';
		document.getElementById('POI_SCHOOL').checked = false;
		clearSummary();
	}

	if (s_layer.length > 0) {
		var elm = getElmById(s_layer);
		if (elm != null) {
			elm.style.visibility  = 'visible';
		}
		s_layer = "";
	}

	
	hideLayer('loading');
    }else alert("Error retreiving data");
 
   okToSend = true;
  } 
}

function postSaveSearch()
{

  	if (okToSend) {
	        http = getHTTPObject();
		
        	if ((http != null) ) {
        		okToSend = false;
        		var dat = getSaveData();

		        http.open("POST", save_url, true);
		        http.onreadystatechange = saveResponse;
		        http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		        showLayer('loading');
		        http.send(dat);
			hideLayer('loading');
        	}
        } else {
                alert ("Waiting for previous response");
        }

	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 createSaveLink()
{
	var link = "";

	if (cookieid.length > 0) 
	{
		link = '<a href="javascript:postSaveSearch()">Save This Search</a>';	
	}
	else 
	{
		link = '<a href="' + root_url + '/vp/LoginServlet2?ScreenID=VOW_LOGIN&SITE=' + site + '&DFLT_PAGE=VOW_HOME&next_url=/vp/jsps/' + site + '/MAPSEARCH_PROXY.jsp?' + createQueryString() + '" target="_parent">Login To Save Searches</a>';
	}

	return link;

}

function processOfficeRecs(offices)
{

        var queryString = createQueryString();

	for (var i = 0; i < offices.length; i++) 
	{
		var nm_O = offices[i].getAttribute('O_NM_OFFICE');

		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_" + nm_O;
                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="' + root_url + cleanString(offices[i].getAttribute('O_WWWSITE')) + '" target="_parent"><img src="' + root_url + cleanString(offices[i].getAttribute('O_DFLT_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_ADDRESS_01')) + '<br />';
		balloon += '<a href="' + root_url + cleanString(offices[i].getAttribute('O_WWWSITE')) + '&mapvars=' + queryString + '%26s_layer%3DmyOffice' + i + '" target="_parent">More Details</a>';
		balloon += '</div>';
		balloon += '</div>';
		balloon += '</div>';

		if (offices[i].getAttribute("O_WWWSITE").length > 0) {

                        myDiv.innerHTML = balloon;

                	mapContainer.appendChild(myDiv);
                        
	                var area = document.createElement('DIV');
        	        area.id = nm_O;
                	area.innerHTML = '<img src="http://www.firstweber.com/img/mapit-search/icon-office.gif" 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.title = nm_O;
        	        area.onmouseover = function() {
				hideAll();
				s_layer = 'OFFICE_' + this.id;
                                document.getElementById('OFFICE_' + this.id).style.visibility = 'visible';
                                open_div = document.getElementById('OFFICE_' + this.id);
                                document.onmousemove = checkPosition;

                	}
                
                mapContainer.appendChild(area); 
		
		}
                
        }       
}
	
function processPropertyRecs(props, numProps)
{

	var props_list = "";

	var queryString = createQueryString();
	
	for (var i = 0; i < props.length; i++) {

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

		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_" + cd_MLS;
		myDiv.style.position='absolute';
		myDiv.style.visibility='hidden';
  		if (s_layer == myDiv.id) {
                        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('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&mapvars=' + queryString + '%26s_layer%3DLISTING_' + cd_MLS +'" target="_parent"><img src="http://' + cleanString(props[i].getAttribute('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">';
		if (props[i].getAttribute('lp_ind_OpenHouse') == 'Y') {
	                balloon += '<div style="font-size:9px;font-face:Arial"><a href="' + root_url + '/vp/ListingServlet?cd_MLS=' + props[i].getAttribute('cd_MLS') + '&SITE=' + site + '&ScreenID=LISTING_DETAIL_P&mapvars=' + queryString + '%26s_layer%3DLISTING_' + cd_MLS + '" target="_parent">Open:' + cleanString(props[i].getAttribute('ds_OpenHouseDay')) + ' ' + cleanString(props[i].getAttribute('ds_OpenHouseTime')) + '</a></div>';
		}	

        	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')) + '<br />';
		if (unescape(props[i].getAttribute('lp_c4v43c')) != 'Vacant+Land/Lots+&+Acreage' && unescape(props[i].getAttribute('lp_c4v43c')) != 'Business/Commercial') {
			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&mapvars=' + queryString + '%26s_layer%3DLISTING_' + 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 = cd_MLS;
	
		if (unescape(props[i].getAttribute('lp_c4v43c')) == 'Vacant+Land/Lots+&+Acreage') {
			area.innerHTML = '<img src="images/icon_land.gif" width="16" height="16" border="0">';
		} else if (unescape(props[i].getAttribute('lp_c4v43c')) == 'Business/Commercial') { 
			area.innerHTML = '<img src="images/icon_commercial.gif" width="16" height="16" border="0">';
		} else {
			area.innerHTML = '<img src="http://mapping.redata.com/plots/arcims/markers/home_yellow.gif" 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() {
  			hideAll();
                        s_layer = 'LISTING_' + this.id;
			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 pcg = getElmById('propcount_alert');
	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");

		if (search_type.length == 0) {
			saveSearch.innerHTML = createSaveLink();
			saveSearch.style.visibility = 'visible';
		}

		pcg.style.visibility = 'hidden';
	
		mapvars.value = unescape(createQueryString());
		theform.style.visibility = 'visible';
		cd_MLS_sum.value = props_list;
		numFound.value = props.length;
		numPages.value = Math.ceil(parseFloat(props.length / 10));
		
	} else {
		theform.style.visibility = 'hidden';
		pcg.style.visibility = 'visible';
		saveSearch.style.visibility = 'hidden';


	}

	if (numProps > 0) {
		pcg.innerHTML = '<span class="alert">Too many to display:</span> Refine your search to fewer than ' + max_results + ' by zooming in closer, or by adjusting the menus at left.';
	} else {
		pcg.innerHTML = '<span class="alert">No properties found:</span> Refine your search to more than 0 by zooming out further, or by adjusting the menus at left.';
	}
			
}

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.visibility='hidden';

                myDiv.style.zIndex=2;
                
                var balloon = '<div class="balloon_' + icon_type + '">';
                balloon += '<div class="inner_balloon_poi">';

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

		if (cleanString(props[i].getAttribute('ds_image')).indexOf('<img') > -1) {
			balloon += cleanString(props[i].getAttribute('ds_image'));
		} else if (cleanString(props[i].getAttribute('ds_image')).length > 0) {
			balloon += '<img src="http://mapping.redata.com/plots/poi/' + site + '/poi/'  + cleanString(props[i].getAttribute('ds_image')) + '" with="150" height="117"><br>';
		}

		if (cleanString(props[i].getAttribute('ds_display')).length > 0) {                                
	                balloon += '<table><tr><td align="left">' + cleanString(props[i].getAttribute('ds_display')) + '</td></tr></table>';
        	} else {
			balloon += cleanString(props[i].getAttribute('ds_text1')) + '<br>';
			balloon += cleanString(props[i].getAttribute('ds_text2')) + '<br>';
			balloon += cleanString(props[i].getAttribute('ds_text3')) + '<br>';
		}
                        
                balloon += '</div>';
                                
                balloon += '</div>';
                                
                myDiv.innerHTML = 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();
                        s_layer = this.id;
                        document.getElementById('POI_' + this.id).style.visibility = 'visible';
			open_div = document.getElementById('POI_' + this.id);
                        document.onmousemove = checkPosition;
                }
                
                mapContainer.appendChild(area);
        
        }
}

