var okToSend = true;
var mindiff = .005;

// tile stuff
var resolution;
var container;
var mapContainer;
var ds = 'ms_search_carru';
var max_results = "100";
var rows = 256;
var cols = 256;
var scale = "";
var max_scale = 9;
var fixedzoom = "";
var cache = "carru";
var cache_origin_x = "-82.50732";
var cache_origin_y = "41.2973";

var s_layer = '';

function getInitialMap(){

        container = document.getElementById('mapArea');

        mapContainer = getElmById('mapContainer');

	getMap("");
}

function write_debug(str)
{
	if (document.getElementById('ta_debug') != null)
	{
		document.getElementById('ta_debug').value += str + '\n';
	}
}

function fixedZoomIn(){
        if (parseInt(scale) < max_scale) {
                scale = parseInt(scale) + 1;
                fixedzoom = "true";
                getMap("");
        } else {
                alert("Currently at min zoom");
        }
}

function fixedZoomOut(){
        if (parseInt(scale) > 0) {
                scale = parseInt(scale) - 1;
                fixedzoom = "true";
                getMap("");
        } else {
                alert ("Currently at max zoom");
        }
}

function zoom(left, bottom, right, top){
     	if (getExtentForZoomIn(left, bottom, right, top)) {
     		getMap("");	
	}
}

function dragObjects(dx, dy)
{
        for (var i = 0; i < container.childNodes.length;i++) {
                var node = container.childNodes[i];
                var cur_left = node.style.left;
                var cur_top = node.style.top;
                var l = parseInt(cur_left.substring(0, cur_left.length));
                var t = parseInt(cur_top.substring(0, cur_top.length));

                node.style.left = parseInt(l +  dx) + "px";
                node.style.top = parseInt(t + dy) + "px";
        }

        for (var i = 0; i < mapContainer.childNodes.length; i++) {
                var node = mapContainer.childNodes[i];
                var cur_left = node.style.left;
                var cur_top = node.style.top;
                var l = parseInt(cur_left.substring(0, cur_left.length));
                var t = parseInt(cur_top.substring(0, cur_top.length));

                node.style.left = parseInt(l +  dx) + "px";
                node.style.top = parseInt(t + dy) + "px";

        }

}

function pan(ix, iy){
	var dx = (maxx - minx)/mwidth;
	var mx = dx*ix;
	var my = dx*iy;
	minx += mx;
	maxx += mx;
	miny += my;
	maxy += my;
	var env = '<ENVELOPE minx="' + minx + '" miny="' + miny +'" maxx="' + maxx +'" maxy="' + maxy + '" />';
     	getMap(env);
}
function panDirection(dir){
	shift(dir);
	getMap("");
}

function shift(dir){
	var dx = maxx - minx;
	var dy = maxy - miny;
		
	switch(dir) {
		//NORTH
		case "north":
			miny += 0.3*dy;
			maxy += 0.3*dy;
		break;
		//south
		case "south":
			miny -= 0.3*dy;
			maxy -= 0.3*dy;
		break;
		//east
		case "east":
			minx += 0.3*dx;
			maxx += 0.3*dx;
		break;
		//west
		case "west":
			minx -= 0.3*dx;
			maxx -= 0.3*dx;
		break;
		//northeast
		case "ne":
			miny += 0.3*dy;
			maxy += 0.3*dy;
			minx += 0.3*dx;
			maxx += 0.3*dx;
		break;
		//northwest
		case "nw":
			miny += 0.3*dy;
			maxy += 0.3*dy;
			minx -= 0.3*dx;
			maxx -= 0.3*dx;
		break;
		//southeast
		case "se":
			miny -= 0.3*dy;
			maxy -= 0.3*dy;
			minx += 0.3*dx;
			maxx += 0.3*dx;
		break;
		//southwest
		case "sw":
			miny -= 0.3*dy;
			maxy -= 0.3*dy;
			minx -= 0.3*dx;
			maxx -= 0.3*dx;
		break
		
	}
}

function getExtentForZoomIn(left, bottom, right, top){

	var LLPoint = getMapXY(left, bottom);
	var URPoint = getMapXY(right, top);
 
	var xdiff = URPoint[0] - LLPoint[0];
        var ydiff = URPoint[1] - LLPoint[1];

        if (xdiff < mindiff || ydiff < mindiff) {
		alert ("Please select a larger area to zoom.");
        	return false;
	}
	
	minx = LLPoint[0];
	miny = LLPoint[1];
	maxx = URPoint[0];
	maxy = URPoint[1];

	return true;

}

function getExtentForZoomOut(left, bottom, right, top){
		var xDiff= maxx-minx;
		var yDiff= maxy-miny;

		var pwidth = right-left;
		var pheight = top-bottom;
		var xRatio = mwidth / pwidth;
		var yRatio = mheight / pheight;
		var xAdd = xRatio * xDiff / 2;
		var yAdd = yRatio * yDiff / 2;
		minx =  minx - xAdd;
		maxx = maxx + xAdd;
		miny = miny - yAdd;
		maxy = maxy + yAdd;
		

}

function dump_vals()
{	
	alert ('minx / ' + minx + ' miny / ' + miny + ' maxx / ' + maxx + ' maxy / ' + maxy);
}

function getMapXY(xIn,yIn) {

	var newValues = new Array();

	var mouseX = xIn;
	var pixelX = (maxx-minx) / mwidth;

	var newX = (pixelX * mouseX) + minx;

	var mouseY = mheight - yIn;
	var pixelY = (maxy-miny) / mheight;
	var newY = (pixelY * mouseY) + miny;

	newValues[0] = newX;

	newValues[1] = newY;
	return newValues; 
}

function growEnvelope(value){
	var dx = maxx - minx;
	var dy = maxy - miny;

	var cx = (maxx + minx)/2.0;
	var cy = (maxy + miny)/2.0;

	var dx1 = 0.5 * value * dx;
	var dy1 = 0.5 * value * dy;

	minx = cx - dx1;
	miny = cy - dy1;
	maxx = cx + dx1;
	maxy = cy + dy1;
}

function getMapWithCurrentExtent(){

	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 getMapRequest(env)
{

	var axl = 'INTERNAL_PLOT=true&SITE=' + site + '&minx=' + minx + '&miny=' + miny + '&maxx=' + maxx + '&maxy=' + maxy + '&width=' + mwidth + '&height=' + mheight + '&cache=' + cache + '&scale=' + scale + '&zoom=' + fixedzoom + '&CACHE_ORIGIN_X=' + cache_origin_x + '&CACHE_ORIGIN_Y=' + cache_origin_y;

	for (var i = 0; i < req_vars.length; i++) {
		axl += '&' + req_vars[i] + '=' + req_vals[i];
	}


	return axl;
}


//need to define loadXML function for non IE browser which do not have loadXML implemented
//we use loadXML (can't use load method) to load ArcXML response because the response from ArcIMS is in plain text format   

if(!isIE && !isSafari){

	Document.prototype.loadXML = function (s) {

	// parse the string to a new doc   
	   	var doc2 = (new DOMParser()).parseFromString(s, "text/xml");
      
	   	// remove all initial children
	   	while (this.hasChildNodes())
	   	   this.removeChild(this.lastChild);
         
	   	// insert and import nodes
	   	for (var i = 0; i < doc2.childNodes.length; i++) {
	   	   this.appendChild(this.importNode(doc2.childNodes[i], true));
	   	}
       };
}



function printResponse(){

if (http.readyState == 4) {
    if (http.status == 200) {

      isWorking = false;
      
	if (!isSafari) 
	{
      	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);
       	}
	} else {
		// Safari
		var xmlDoc = http.responseXML;
	}

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

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

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

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

	processPropertyRecs(props);
	processOfficeRecs(offices);

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

   okToSend = true;

  }
 
}

function positionSlider() {
	document.getElementById('sliderImg').style.top = (165 - (parseInt(scale) * 10)) + 'px';
}

function placeTiles(tiles) {
        for (var i = 0; i < tiles.length; i++) {
                var url = tiles[i].getAttribute("url");

                        var x = parseFloat(tiles[i].getAttribute("x"));
                        var y = parseFloat(tiles[i].getAttribute("y"));
                        var row = parseInt(tiles[i].getAttribute("row"));
                        var col = parseInt(tiles[i].getAttribute("col"));
                        var x_pos = parseInt((x - minx)/resolution);
                        var y_pos = parseInt((maxy - y)/resolution);

                        var img = document.createElement('img');

                        img.src = url;
                        img.style.position = 'absolute';
                        img.style.top = y_pos + 'px';
                        img.style.left = x_pos + 'px';
                        img.onload = null;

                        container.appendChild(img);
        }

}

function jumpTo(i) {
        if (okToSend) {
                scale = i;
                fixedzoom = "true";
                getMap("");
        }
}



function cleanString(str) 
{
	return unescape(str.replace(new RegExp(/\+/g), ' '));
}

function getElmById(theID) {
	var rv = null;

	if (isIE) {
		rv = document.all[theID];
	} else {
		rv = document.getElementById(theID);
	}
	return rv;
}

function clearImageMap ()
{
        while (mapContainer.childNodes.length > 0) {
                mapContainer.removeChild(mapContainer.lastChild);
        }

        while (container.childNodes.length > 0) {
                container.removeChild(container.lastChild);
        }

}	


function processOfficeRecs(offices)
{


        var icon_w = 206;
        var icon_h = 237;

        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 = "myOffice" + i;
                myDiv.style.position='absolute';
                myDiv.style.visibility='hidden';
                myDiv.style.left =x + 'px';
                myDiv.style.top = y + 'px';
                myDiv.style.width = '160px';
                myDiv.style.height= '220px';
                myDiv.style.zIndex=2;

                var photo_string = "";

                photo_string = '<img src="' + root_url + '/images/offices/' + cleanString(offices[i].getAttribute('O_CD_OFFICE')) + '.jpg" width="150" height="117" border="0">';

                var balloon = '<div class="balloon_' + icon_type + '">';
                balloon += '<div class="inner_balloon">';
                balloon += '<div class="close_icon"><a href="#" onClick="document.getElementById(\'myOffice' + i + '\').style.visibility=\'hidden\';"><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 += '</div>';
                balloon += '</div>';
                balloon += '</div>';

             	myDiv.innerHTML = balloon;

                mapContainer.appendChild(myDiv);

                var area = document.createElement('DIV');
                area.id = i;
                area.innerHTML = '<img src="images/mapgif_star.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.onclick = function() {
			hideAll();
                	document.getElementById('myOffice' + this.id).style.visibility = 'visible';
              	}

                mapContainer.appendChild(area);

		var dist = document.getElementById('mileMarker').value;
                if (dist.length > 0) {
                        addMileMarker(dist, offices[i].getAttribute("O_RES_LAT"), x1, y1);
                }

	}

}


function processPropertyRecs(props)
{

        var props_list = "";

        var icon_w = 206;
        var icon_h = 237;

        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 = "myLayer" + i;
                myDiv.style.position='absolute';
                myDiv.style.visibility='hidden';
                myDiv.style.left =x + 'px';
                myDiv.style.top = y + 'px';
                myDiv.style.width = '160px';
                myDiv.style.height= '220px';
                myDiv.style.zIndex=2;

                var photo_string = "";

                if (props[i].getAttribute('LP_PHOTO_URL').length > 0) {
                        photo_string = '<img src="http://' + cleanString(props[i].getAttribute('LP_PHOTO_URL')) + props[i].getAttribute('L_MLS_NUMBER') + 'at.jpg" width="150" height="117" border="0">';
                }

   		var balloon = '<div class="balloon_' + icon_type + '">';
                balloon += '<div class="inner_balloon">';
                balloon += '<div class="close_icon"><a href="#" onClick="document.getElementById(\'myLayer' + i + '\').style.visibility=\'hidden\';"><img border="0" src="images/close_icon.gif" style="width:17px;"></a></div>';
		balloon += photo_string; 
                balloon += '<div class="address">' + cleanString(props[i].getAttribute('L_LISTINGADDR1')) + '</div>';
 		var price = props[i].getAttribute('LS_AMT_SALE_PRICE') != null && props[i].getAttribute('L_LISTINGSTATUS') == 'Sold' ? props[i].getAttribute('LS_AMT_SALE_PRICE') : props[i].getAttribute('L_LISTING_PRICE');

                balloon += '$' + cleanString(formatPrice(price)) + '<br />';
		if (props[i].getAttribute('L_CD_SOURCE') == 'ARIS') {
                	balloon += props[i].getAttribute('LS_NO_BEDROOMS') + ' Beds ' + props[i].getAttribute('LS_NO_BATHROOMS') + ' Baths<br>';
		} else {
                	balloon += props[i].getAttribute('LS_NO_BEDROOMS') + ' Beds ' + props[i].getAttribute('LDID_I48NT') + '.' + props[i].getAttribute('LDID_I49NT') + ' Baths<br>';
		}
                balloon += '</div>';
                balloon += '</div>';
                balloon += '</div>';

                myDiv.innerHTML = balloon;

                mapContainer.appendChild(myDiv);
        
                var area = document.createElement('DIV');
 		area.id = i;
		if (findVal('INC_LABELS') == 'true') {
                	area.innerHTML = '<img src="images/mapgif_house.gif" border="0"><b> ' + (i+1) + '</b>';
		} else {
                	area.innerHTML = '<img src="images/mapgif_house.gif" border="0">';
		}
                area.style.left=(x1 - 8) + 'px';
                area.style.top=(y1 - 8)+ 'px';
                area.style.position='absolute';
                area.style.zIndex=1;
                area.onclick = function() {
			hideAll();
			s_layer = 'myLayer' + this.id;
                        document.getElementById(s_layer).style.visibility = 'visible';
                }

                mapContainer.appendChild(area);

		var dist = document.getElementById('mileMarker').value;
		if (dist.length > 0) {
			addMileMarker(dist, props[i].getAttribute("LL_RES_LAT"), x1, y1);
		}
        }

	if (props.length > 0) {
		buildListingRouteTable(props);
	}
	
}

function addMileMarker(dst, val, x, y){
	var w = getCircleRadius(dst, val);
	var img = document.createElement('img');
	img.src = 'http://mapping.redata.com/mapping_v2006/jsps/COMMON/trans_cir.png';
        img.style.position = 'absolute';
        img.style.top = (parseInt(y) - w) + 'px';
        img.style.left = (parseInt(x) - w) + 'px';
	img.style.width = (w * 2) + 'px';
	img.style.height = (w * 2) + 'px';
        img.onload = null;

        container.appendChild(img);
}

function hideAll()
{
        var els = document.getElementsByTagName('DIV');

        for (var j = 0; j < els.length; j++) {
                var elm = els[j];
                if (elm != null) {
                        if (elm.id.indexOf('myLayer') > -1 || elm.id.indexOf('myOffice') > -1)
                                elm.style.visibility = 'hidden';
                } else {
                        break;
                }
        }
}

function formatPrice(price) {
	var nf = new NumberFormat();
	nf.setNumber(price);
	nf.setPlaces(0);
	return nf.toFormatted();
}

function findVal(val) {
	for (var i = 0; i < req_vars.length; i++) {
		if (req_vars[i] == val) {
			return req_vals[i];
		}
	}
	return "";
}
