var ds = 'ms_search_santafe';
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);


        }

    } else {
        alert ("Waiting for previous response");
    }
}

function getTiledMapRequest(env)
{

    var w = buildWhere();

    var w_poi = '';

    if(typeof buildPoiWhere == 'function') {
        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_ListingZip,cd_Company,lp_ListingCity";

    var elm_val = "";

    var elm = getElmById('INC_OFFICES');

    if (elm){
        if (elm.checked){
            elm_val="true";
        }
    }

    var axl = 'SITE=' + site + '&INC_OFFICES=' + elm_val + '&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 + "&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;

            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"));
 	document.getElementById('minx').value=minx;
        document.getElementById('miny').value=miny;
	document.getElementById('maxx').value=maxx;
        document.getElementById('maxy').value=maxy;
        document.getElementById('scale').value=scale;

            clearImageMap();

            placeTiles(tiles);

            fixedzoom = "";

            var props = xmlDoc.getElementsByTagName("PROPERTY");
            var offices = xmlDoc.getElementsByTagName("OFFICE");
            var pois = xmlDoc.getElementsByTagName("POI");

	document.getElementById('propcount').innerHTML = '<span class="form_label"><font size="2px" color="#002349">Property Count: ' + xmlDoc.getElementsByTagName("PROPERTIES").item(0).getAttribute("count") + ' (Properties display for counts less than ' + max_results + ')</font></span>';

        processOfficeRecs(offices);
	processPropertyRecs(props, xmlDoc.getElementsByTagName("PROPERTIES").item(0).getAttribute("count"));

	display_stats(props);

        if (props.length > 0) {
        	createSummary(props);
        } else {
        	clearSummary();
        }

            hideLayer('loading');

        }else alert("Error retreiving data");

        okToSend = true;
    }
}

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', 'area');

        for (var i = 0; i < myvars.length; i++) {
                retVal = retVal + "&" + myvars[i] + "=" + getElmById(myvars[i]).value;
        }
	if (getCheckedValue(document.getElementById('s_type_santafe_listings')).length > 0) {
		retVal += "&s_type=santafe_listings";
	}
	if (getCheckedValue(document.getElementById('s_type_santafe_newly_priced')).length > 0) {
		retVal += "&s_type=santafe_newly_priced";
	}
	if (getCheckedValue(document.getElementById('s_type_new_listings')).length > 0) {
		retVal += "&s_type=new_listings";
	}
	if (getCheckedValue(document.getElementById('s_type_open_houses')).length > 0) {
		retVal += "&s_type=open_houses";
	}

        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 area = document.getElementById('area').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 = '" + p_type + "'";
        }

	if (area.length > 0) {
		w += " AND lp_cd_Area = '" + area + "'";
	}

	if (getCheckedValue(document.getElementById('s_type_santafe_listings')).length > 0) {
		w += " AND cd_Company = 'SANTAFE'";
	}
	if (getCheckedValue(document.getElementById('s_type_santafe_newly_priced')).length > 0) {
		w += " AND dt_Listing_PriceChg > DATE_ADD(NOW(), INTERVAL -7 DAY)";
	}
	if (getCheckedValue(document.getElementById('s_type_new_listings')).length > 0) {	
		w += " AND lp_Listing_Date > DATE_ADD(NOW(), INTERVAL -7 DAY)";
	}
	if (getCheckedValue(document.getElementById('s_type_open_houses')).length > 0) {
		w += " AND lp_ind_OpenHouse = 'Y'";
	}

        return w;
}

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';
                if (s_layer == cleanString(offices[i].getAttribute('O_NM_OFFICE'))) {
                        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 = "";

               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="/mapping_v2006/jsps/COMMON/ts_us/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 += '</div>';
                balloon += '</div>';
                balloon += '</div>';


                        myDiv.innerHTML = balloon;

                        mapContainer.appendChild(myDiv);

                        var area = document.createElement('DIV');
                        area.id = i;
			
                        area.innerHTML = '<img src="images/sfp_logo_map.jpg" 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 processPropertyRecs(props, numProps)
{


	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_P&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 + '/vp/ListingServlet?cd_MLS=' + props[i].getAttribute('cd_MLS') + '&SITE=' + site + '&ScreenID=LISTING_DETAIL_P&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">';                
		if (props[i].getAttribute('lp_ind_OpenHouse') == 'Y') {                       
			if (pres_agent.length > 0) {
                                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=AGENT_LISTING_DETAIL_P&pres_agent=' + pres_agent + '&mapvars=' + queryString + '%26s_layer%3D' + props[i].getAttribute('cd_MLS')  + '" target="_parent">Open:' + cleanString(props[i].getAttribute('lp_ds_OpenHouseDay')) + ' ' + cleanString(props[i].getAttribute('lp_ds_OpenHouseTime')) + '</a></div>';
                        } else {
                        	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%3D' + props[i].getAttribute('cd_MLS') + '" target="_parent">Open:' + cleanString(props[i].getAttribute('lp_ds_OpenHouseDay')) + ' ' + cleanString(props[i].getAttribute('lp_ds_OpenHouseTime')) + '</a></div>';
			}
                }

 balloon += '<div class="close_icon">' + (props[i].getAttribute('cd_Company') == 'SANTAFE' ? '<img src="images/sfp_logo_map.jpg" style="width:24px;left:-120px;position:relative">' : '<img src="images/idx_logo.jpg" style="width:24px;left:-120px;position:relative">') + '<a href="javascript:hideAll();"><img border="0" src="/mapping_v2006/jsps/COMMON/ts_us/images/close_icon.gif" style="width:17px;position:relative;left:-10px"></a></div>';

                balloon += photo_string;
                balloon += '<div class="address">' + cleanString(props[i].getAttribute('lp_ListingAddr1')) + ' ' + cleanString(props[i].getAttribute('lp_ListingZip')) + '</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_P&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 + '/vp/ListingServlet?cd_MLS=' + props[i].getAttribute('cd_MLS') + '&SITE=' + site + '&ScreenID=LISTING_DETAIL_P&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[i].getAttribute('cd_Company') == 'SANTAFE' && props[i].getAttribute('lp_ind_OpenHouse') != 'Y') {
                area.innerHTML = '<img src="images/sfp.gif" border="0">';
                } else if (props[i].getAttribute('lp_ind_OpenHouse') == 'Y') {
		area.innerHTML = '<img src="images/gold-house.gif" border="0">';
		} else {
                area.innerHTML = '<img src="images/sfp_house_bw.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();
			document.getElementById('LISTING_' + this.id).style.visibility = 'visible';
                        open_div = document.getElementById('LISTING_' + this.id);
                        document.onmousemove = checkPosition;

                }
                mapContainer.appendChild(area);

	}
}


