/* -*- mode: java -*- */

/*****************************************
 * Copyright (c) 2006, Emmett M. Pate, Jr.
 * emmett@epate.com
 *
 */
 
function getHTTPObject()
{
 var xmlhttp;
 /*@cc_on
 @if (@_jscript_version >= 5)
 try {
  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
   try {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (E) {
    xmlhttp = false;
   }
  } @else xmlhttp = false;
   @end @*/
   if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
   try {
    xmlhttp = new XMLHttpRequest();
   } catch (e) {
   xmlhttp = false;
  }
 }
 return xmlhttp;
}
var mapobj = getHTTPObject(); // We create the HTTP Object
var sumobj = getHTTPObject(); // We create the HTTP Object
var detobj = getHTTPObject(); // We create the HTTP Object

function Search(offset)
{
    urchinTracker('/commidx/search');

    statsDiv = document.getElementById('stats');
    statsDiv.style.textAlign = "center";
    statsDiv.innerHTML = "<div style=\"position:relative;top:16\"><img src=/graphics/wait.gif></div>";

    listingsDiv = document.getElementById('listings');
    height = parseInt(listingsDiv.style.height);

    sumDiv = document.getElementById('sum');
    sumDiv.style.textAlign = "center";
    if (parseInt(sumDiv.style.height) > 200)
	{
	    sumDiv.innerHTML = "<div style=\"position:relative;top:" + parseInt(sumDiv.style.height) / 2 + "\"><img src=/graphics/wait.gif></div>";
	}

    // GUnload();
    if (typeof(map) == 'undefined')
	{
	    map = new GMap2(document.getElementById("map"));
	    map.addControl(new GSmallMapControl());
	    map.addControl(new GMapTypeControl());
	    CreateResetControl();
	    map.setCenter(new GLatLng(36.865247, -76.168358), 7);
	}
    // clear existing overlays
    map.clearOverlays();

    // Null Icon
    var NullIcon = new GIcon();
    NullIcon.image = "/graphics/nullicon.png";
    NullIcon.shadow = "/graphics/nullicon.png";
    NullIcon.iconSize = new GSize(2, 2);
    NullIcon.shadowSize = new GSize(2, 2);
    NullIcon.iconAnchor = new GPoint(1, 1);
    NullIcon.infoWindowAnchor = new GPoint(1, 1);
    var marker = new PdMarker(map.getCenter(), NullIcon);
    marker.setTooltip("Searching...");
    marker.setOpacity(100);
    map.addOverlay(marker);
    marker.showTooltip();

    var str = "";
    for (i=0; i<document.ps.length; i++)
	{
	    str = str + document.ps.elements[i].name + "=";
	    if (document.ps.elements[i].type == "checkbox")
		{
		    str += (document.ps.elements[i].checked ? 1 : 0) + "&";
		}
	    else
		{
		    str += escape(document.ps.elements[i].value) + "&";
		}
	    
	}
    str += "pg=" + offset;
    str += "&width=" + (parseInt(sumDiv.style.width) - 5);
    str += "&height=" + height;
    ShowSummary(str);

}

function ShowSummary(str)
{
    sumobj.open("GET", "/commidx/cgi-bin/ShowSummary.cgi?"+str, true);
    sumobj.onreadystatechange = function() {
	if (sumobj.readyState == 4) {
	    var xml = GXml.parse(sumobj.responseText);

	    sumDiv = document.getElementById('sum');
	    sumDiv.innerHTML = xml.documentElement.getElementsByTagName("results")[0].firstChild.nodeValue;

	    statsDiv = document.getElementById('stats');
	    /* statsDiv.style.backgroundColor = "#F6F6F6"; */
	    statsDiv.innerHTML = xml.documentElement.getElementsByTagName("statistics")[0].firstChild.nodeValue;

	    ShowMap(xml);
	}
    }
    sumobj.send(null);
}

var map;
var center, zoom;

function ShowMap(xml)
{
    function createMarker(point, icon, html, address, num)
	{
	    /* var marker = new GMarker(point, icon); */
	    var marker = new PdMarker(point, icon);
	    marker.setOpacity(100);
	    GEvent.addListener(marker, "mouseover", function() {
		marker.setTooltip(address)
		    });
	    GEvent.addListener(marker, "mouseout", function() {
		marker.hideTooltip()
		    });
	    GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html)
		    });
	    GEvent.addDomListener(document.getElementById("item-"+num), "mouseover", function() {
		marker.openInfoWindowHtml(html);
		map.setCenter(point, 15);
	    });

	    return marker;
	}

    // use Googles "tiny" icon
    var BlueIcon = new GIcon();
    var RedIcon = new GIcon();
    BlueIcon.image = "/graphics/mm_20_blue.png";
    BlueIcon.shadow = "/graphics/mm_20_shadow.png";
    BlueIcon.iconSize = new GSize(12, 20);
    BlueIcon.shadowSize = new GSize(22, 20);
    BlueIcon.iconAnchor = new GPoint(6, 20);
    BlueIcon.infoWindowAnchor = new GPoint(5, 1);
    RedIcon.image = "/graphics/wew_20_red.png";
    RedIcon.shadow = "/graphics/wew_20_shadow.png";
    RedIcon.iconSize = new GSize(20, 20);
    RedIcon.shadowSize = new GSize(40, 20);
    RedIcon.iconAnchor = new GPoint(9, 20);
    RedIcon.infoWindowAnchor = new GPoint(5, 1);
    
    var listings = xml.documentElement.getElementsByTagName("listing");
    var bounds = new GLatLngBounds;
    for (var i=0; i<listings.length; i++)
    {
	var point = new GLatLng(parseFloat(listings[i].getElementsByTagName("marker")[0].getAttribute("lat")),
				parseFloat(listings[i].getElementsByTagName("marker")[0].getAttribute("lng")));
	map.addOverlay(createMarker(point,
				    /* listings[i].getAttribute("broker") == 470 ? RedIcon : BlueIcon, */
				    RedIcon,
				    listings[i].getElementsByTagName("overlay")[0].childNodes[0].nodeValue,
				    listings[i].getAttribute("address"),
				    i
			   ));
	// bounds.extend(point);
    }

    var marker = map.getFirstMarker();
    map.removeOverlay(marker); // this removes the "Searching..." overlay
    map.zoomToMarkers(5); // pdMarker extension
    center = map.getCenter(); // save these for "Reset" control
    zoom = map.getZoom();

    /*
    if (listings.length)
    {
	map.setCenter(new GLatLng((bounds.getSouthWest().y + bounds.getNorthEast().y)/2,
				  (bounds.getSouthWest().x + bounds.getNorthEast().x)/2),
		      map.getBoundsZoomLevel(bounds));
	center = map.getCenter();
	zoom = map.getZoom();
    }
    */
}

function ShowMapOnDetail(lat, lon) {
    var RedIcon = new GIcon();
    RedIcon.image = "/graphics/mm_20_red.png";
    RedIcon.shadow = "/graphics/mm_20_shadow.png";
    RedIcon.iconSize = new GSize(12, 20);
    RedIcon.shadowSize = new GSize(22, 20);
    RedIcon.iconAnchor = new GPoint(6, 20);
    RedIcon.infoWindowAnchor = new GPoint(5, 1);

    var point = new GLatLng(lat, lon);
    var marker = new GMarker(point, RedIcon);
    map = new GMap2(document.getElementById("photo"));
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(point, 15);
    map.addOverlay(marker);
}

function setMapView(lat, lng)
{
    map.setCenter(new GLatLng(lat,lng), 15);
}

function TextualResetControl() {
}

function CreateResetControl()
{
    TextualResetControl.prototype = new GControl();
    
    TextualResetControl.prototype.initialize = function(map)
	{
	    var container = document.createElement("div");
	    var resetDiv = document.createElement("div");
	    
	    this.setButtonStyle_(resetDiv);
	    container.appendChild(resetDiv);
	    resetDiv.appendChild(document.createTextNode("Reset"));
	    GEvent.addDomListener(resetDiv, "click", function() {
				      map.setCenter(center, zoom);
				  });
	    
	    map.getContainer().appendChild(container);
	    return container;
	}
    
    TextualResetControl.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(7, 7));
    }

    TextualResetControl.prototype.setButtonStyle_ = function(button) {
	button.style.textDecoration = "none";
	button.style.color = "black";
	button.style.backgroundColor = "white";
	button.style.font = "12px Arial";
	button.style.border = "1px solid black";
	button.style.padding = "2px";
	button.style.marginBottom = "2px";
	button.style.textAlign = "center";
	button.style.width = "3em";
	button.style.cursor = "pointer";
    }
    map.addControl(new TextualResetControl());
}

var DetailsWindow;
function ShowDetails(mls,agent)
{
    urchinTracker('/commidx/details/'+mls);

    var url = "/commidx/cgi-bin/ShowDetails.cgi?mls="+mls+"&agent="+agent;
    var agent = navigator.userAgent;
    if (DetailsWindow && !DetailsWindow.closed) {
	DetailsWindow.document.write();
	DetailsWindow.document.close();
    }
    DetailsWindow = window.open(url,'DetailsWindow','toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,copyhistory=no,width=850,height=800,scrollbars=yes');

    return 0;
}

var photos;
function ShowImage(n) {

    photoDiv = document.getElementById('photo');
    if (! photoDiv) { return; }
    if (! photos && lat && lon) { ShowMapOnDetail(lat, lon); return; }
    if (! photos) { return; }

    photoDiv.style.backgroundColor = "white";
    photoDiv.style.textAlign = "center";
    photoDiv.innerHTML = photos[n];
}

// Katabat Form
function KatabatRequest(theLink,src) {
	var initialX =	100;
	var initialY = 100;
	urchinTracker('/contact/moreinfo');
	// theLink = theLink + "&o2=" + decodeBase64(src);
	theLink = theLink + "&o2=" + src;
	if (navigator.appName == "Netscape") {
		theWindow = open( theLink, "Lookup", "width=510,height=560," +
			"screenX=" + initialX + ",screenY=" + initialY +
			",scrollbars,resizable");
		theWindow.focus(); // make sure our new window is in front
	} else {
		theWindow = open( theLink, "Lookup", "width=500,height=560" +
			",left=" + initialX + ",top=" + initialY +
			",scrollbars,resizable");
	}
	theWindow.opener = self;
}	

var base64Chars = new Array(
    'A','B','C','D','E','F','G','H',
    'I','J','K','L','M','N','O','P',
    'Q','R','S','T','U','V','W','X',
    'Y','Z','a','b','c','d','e','f',
    'g','h','i','j','k','l','m','n',
    'o','p','q','r','s','t','u','v',
    'w','x','y','z','0','1','2','3',
    '4','5','6','7','8','9','+','/'
);
var END_OF_INPUT = -1;
var reverseBase64Chars = new Array();
for (var i=0; i < base64Chars.length; i++){
    reverseBase64Chars[base64Chars[i]] = i;
}
var base64Str;
var base64Count;
function setBase64Str(str){
    base64Str = str;
    base64Count = 0;
}
function readReverseBase64(){   
    if (!base64Str) return END_OF_INPUT;
    while (true){      
        if (base64Count >= base64Str.length) return END_OF_INPUT;
        var nextCharacter = base64Str.charAt(base64Count);
        base64Count++;
        if (reverseBase64Chars[nextCharacter]){
            return reverseBase64Chars[nextCharacter];
        }
        if (nextCharacter == 'A') return 0;
    } 
}
function ntos(n){
    n=n.toString(16);
    if (n.length == 1) n="0"+n;
    n="%"+n;
    return unescape(n);
}
function decodeBase64(str){
    setBase64Str(str);
    var result = "";
    var inBuffer = new Array(4);
    var done = false;
    while (!done && (inBuffer[0] = readReverseBase64()) != END_OF_INPUT
        && (inBuffer[1] = readReverseBase64()) != END_OF_INPUT){
        inBuffer[2] = readReverseBase64();
        inBuffer[3] = readReverseBase64();
        result += ntos((((inBuffer[0] << 2) & 0xff)| inBuffer[1] >> 4));
        if (inBuffer[2] != END_OF_INPUT){
            result +=  ntos((((inBuffer[1] << 4) & 0xff)| inBuffer[2] >> 2));
            if (inBuffer[3] != END_OF_INPUT){
                result +=  ntos((((inBuffer[2] << 6)  & 0xff) | inBuffer[3]));
            } else {
                done = true;
            }
        } else {
            done = true;
        }
    }
    return result;
}

var Calc;
function Payment(P)
{
if (Calc && !Calc.closed) {
		Calc.document.write();
		Calc.document.close();
	}
	Calc = window.open('/cgi-bin/payment.cgi?price='+P,'Calc','toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,copyhistory=no,scrollbars=no,width=390,height=420');
}

var mySherlock;
function SaveSearch()
{
    var str = "";
    for (i=0; i<document.ps.length; i++)
	{
	    str = str + document.ps.elements[i].name + "=";
	    if (document.ps.elements[i].type == "checkbox")
		{
		    str += (document.ps.elements[i].checked ? 1 : 0) + "&";
		}
	    else
		{
		    str += escape(document.ps.elements[i].value) + "&";
		}
	    
	}
    str += "ls=COMM";
    if (mySherlock && !mySherlock.closed) {
	mySherlock.document.write();
	mySherlock.document.close();
    }
    else {
	mySherlock = window.open('/commidx/cgi-bin/SaveSearch.cgi?'+str,'mySherlock','toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,copyhistory=no,scrollbars=no,width=370,height=220');
    }
}

var mySherlock
function SaveProperty(MLS,LS) {
	if (mySherlock && !mySherlock.closed) {
		mySherlock.document.write();
		mySherlock.document.close();
	}
	else {
		mySherlock = window.open('/cgi-bin/saveproperty.cgi?mls='+MLS+'&ls='+LS,'mySherlock','toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,copyhistory=no,scrollbars=no,width=370,height=220');
	}
}

var Feedback;
function RequestFeedback()
{
    Feedback = window.open('feedback.html','Feedback','toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,copyhistory=no,scrollbars=no,width=350,height=220');
}

function initPage()
{
    setupForm(); /* setup the COMM form elements */
    Resize();    /* Resize the divisions */
    Search(0)    /* initial search results */
}

function Resize()
{
    headerDiv = document.getElementById('header');
    mapDiv = document.getElementById('map');
    prefDiv = document.getElementById('prefs');
    statsDiv = document.getElementById('stats');
    sumDiv = document.getElementById('sum');
    keyDiv = document.getElementById('keytab');
    commDiv = document.getElementById('comm');
    footerDiv = document.getElementById('footer');

    if (document.body.clientWidth < 800)
	{
	    headerDiv.style.width = 785;
	    mapDiv.style.width = 400;
	    statsDiv.style.width = 400;
	    sumDiv.style.width = 785;
	    keyDiv.style.width = 785;
	    commDiv.style.width = 785;
	    footerDiv.style.width = 785;
	}
    else
	{
	    headerDiv.style.width = document.body.clientWidth - 10;
	    mapDiv.style.width = document.body.clientWidth - 380 - 15;
	    statsDiv.style.width = document.body.clientWidth - 380 - 15;
	    sumDiv.style.width = document.body.clientWidth - 10;
	    keyDiv.style.width = document.body.clientWidth - 10;
	    commDiv.style.width = document.body.clientWidth - 10;
	    footerDiv.style.width = document.body.clientWidth - 10;
	}

}

function ResizeDetails()
{
    photoDiv = document.getElementById('photos');
    featuresDiv = document.getElementById('features');
    afeaturesDiv = document.getElementById('afeatures');

    photoDiv.style.width = document.body.clientWidth - 300 - 20;
    featuresDiv.style.width = document.body.clientWidth - 10;
    afeaturesDiv.style.width = document.body.clientWidth - 10;
}

// RollUp top 4 panels
// quick browser tests
var ns4 = (document.layers) ? true : false;
var ie4 = (document.all && !document.getElementById) ? true : false;
var ie5 = (document.all && document.getElementById) ? true : false;
var ns6 = (!document.all && document.getElementById) ? true : false;

function ShadeUp() {
    // hide the divisions
    formandmapDiv = document.getElementById('formandmap');
    sumContainer = document.getElementById('summary');
    sumDiv = document.getElementById('sum');
    sumtabDiv = document.getElementById('sumtab');
    listingsDiv = document.getElementById('listings');
    keyDiv = document.getElementById('key');
    commDiv = document.getElementById('comm');
    footerDiv = document.getElementById('footer');

    formandmapDiv.style.visibility = 'hidden';
    sumContainer.style.top = 100;

    sumContainer.style.height = document.body.clientHeight - 100 - 20;
    sumDiv.style.height = document.body.clientHeight - 100 - 20;
    listingsDiv.style.height = document.body.clientHeight - 100 - 50;
    keyDiv.style.top = document.body.clientHeight;
    commDiv.style.top = document.body.clientHeight + 90;
    footerDiv.style.top = document.body.clientHeight + 90 + 55;

    sumDiv.style.overflow = 'visible';
    sumtabDiv.innerHTML = "<b class=\"tab\"><a href=\"javascript:ShadeDown();\">summary [&ndash;]</a></b>";
}
function ShadeDown() {
    // show the divisions
    formandmapDiv = document.getElementById('formandmap');
    sumContainer = document.getElementById('summary');
    sumDiv = document.getElementById('sum');
    sumtabDiv = document.getElementById('sumtab');
    listingsDiv = document.getElementById('listings');
    keyDiv = document.getElementById('key');
    commDiv = document.getElementById('comm');
    footerDiv = document.getElementById('footer');

    formandmapDiv.style.visibility = 'visible';
    sumContainer.style.top = 622;
    sumContainer.style.height = 200;
    listingsDiv.style.height = 170;
    keyDiv.style.top = 842;
    commDiv.style.top = 932;
    footerDiv.style.top = 975;
    sumDiv.style.height = 200;
    sumtabDiv.innerHTML = "<b class=\"tab\"><a href=\"javascript:ShadeUp();\">summary [+]</a></b>";
}
