/* -*- JavaScript -*-
# The leading '#'s are just for consistency with other text formats
#
# rdf:
# dc:title General scripting support for norman.walsh.name
# dc:date 2004-03-19
# cvs:date $Date$
# dc:creator http://norman.walsh.name/knows/who#norman-walsh
# dc:description JavaScript for stylesheet switching. Stolen from ongoing.
*/

/*
function showLinkGroup(file) {
  window.open(file, "LinkGroup", "width=600,height=600,scrollbars=yes,toolbar=no");
  return false;
}
*/

function addpLinks() {
    var paras = document.getElementsByTagName('p');
    for (var i = 0; i < paras.length; i++) {
	var current = paras[i];
	if (current.id != '') {
	    var plink = document.createElement('a');
	    plink.href = document.location.href.split('#')[0] +
		'#' + current.id;
	    plink.className = 'plink';
	    plink.appendChild(document.createTextNode(' ¶'));
	    current.appendChild(plink);
	}
    }
}

function addSidebarClose() {
    var close = document.getElementById('close');
    var img = document.createElement('img');
    img.setAttribute("src","/graphics/close-sidebar.png");
    img.setAttribute("alt","[X]");
    img.setAttribute("border", "0");
    var a = document.createElement('a');
    a.setAttribute("class", "plain");
    a.href = "javascript:closeSidebar()";
    a.appendChild(img);
    close.appendChild(a);
}

function closeSidebar() {
    var sidebar = document.getElementById('sidebar');
    var content = document.getElementById('content');
    sidebar.style.display = 'none';
    content.style.marginRight = "20px";
}

// Ajax...

var xmlReqs = new Array();

function ReqObj(type, xmlhttp) {
    this.type = type;
    this.xmlhttp = xmlhttp;
}

function getReqObj() {
    // JavaScript is single threaded, right?
    // I used to try to cache xmlReq objects, but it seemed to cause weird
    // problems. Presumably GC cleans them up...right?
    /*
    for (var i = 0; i < xmlReqs.length; i++) {
        if (xmlReqs[i].type == 'ready') {
            xmlReqs[i].type = "busy";
	    xmlReqs[i].xmlhttp.abort(); // for IE
            return xmlReqs[i];
        }
    }
    */

    var req = false;
    if (window.XMLHttpRequest) {
        // branch for native XMLHttpRequest object
        req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        // branch for IE/Windows ActiveX version
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }

    var reqobj = new ReqObj("busy", req);
    xmlReqs.push(reqobj);
    return reqobj;
}

function loadXMLDoc(url) {
    var req = getReqObj();
    if (window.XMLHttpRequest) {
        // branch for native XMLHttpRequest object
        req.xmlhttp.onreadystatechange = processReqChange;
        req.xmlhttp.open("GET", url, true);
        req.xmlhttp.send(null);
    } else if (window.ActiveXObject) {
        // branch for IE/Windows ActiveX version
        if (req.xmlhttp) {
            req.xmlhttp.onreadystatechange = processReqChange;
            req.xmlhttp.open("GET", url, true);
            req.xmlhttp.send();
        }
    }
}

function processReqChange() {
    for (var i = 0; i < xmlReqs.length; i++) {
        if (xmlReqs[i].type == "busy" && xmlReqs[i].xmlhttp.readyState == 4) {
            handleResponse(xmlReqs[i].xmlhttp);
            xmlReqs[i].type = "ready";
        }
    }
}

function handleResponse(req) {
    // Only ever called when req is complete...
    if (req.status == 200) {
        // ...processing statements go here...
        var response  = req.responseXML.documentElement;
        var method = response.getElementsByTagName('method')[0].firstChild.data;
	var found = response.getElementsByTagName('found')[0].firstChild.data;

	if (found != "0") {
	    var result = "";
	    var title = "";
	    var rwrap = response.getElementsByTagName('result')[0];
	    var elem = rwrap.firstChild;
	    while (elem != null) {
		result += elem.data;
		elem = elem.nextSibling;
	    }
	    elem = response.getElementsByTagName('title')[0].firstChild;
	    if (elem != null) {
		title = elem.data;
	    }
	    eval(method + '(result,title)');
	}
    } else {
        alert("There was a problem retrieving the XML data:\n" + req.status + ": " + req.statusText);
    }
}

function setupNextLink(response, title) {
    var about = document.location.toString().substring(7); // skip http://
    about = about.substring(about.indexOf("/"));

    var span = document.getElementById('nextlink');

    if (response != '') {
        // Response mode
        if (response != '') {
	    var div = document.createElement("span");
	    div.className = "div";
	    div.appendChild(document.createTextNode(" / "));
	    var a = document.createElement("a");
	    a.setAttribute("href", response);
	    //a.setAttribute("title", title);
	    a.appendChild(document.createTextNode("→"));
	    span.appendChild(div);
	    span.appendChild(a);
        }
    } else {
        // Input mode
	if (span != null) {
	    url = '/cgi-bin/ajaxnav?method=setupNextLink';
	    url = url + '&page=next&about=' + about;
	    loadXMLDoc(url);
	}
    }
}

function addTweet(response,title) {
    var tweet = document.getElementById('tweet');

    if (tweet == null) {
	return;
    }

    if (response != '') {
        // Response mode
	var a = document.createElement("a");
	a.setAttribute("href", "http://twitter.com/ndw");
	a.setAttribute("title", "Tweet!");
	a.appendChild(document.createTextNode(title));
	tweet.appendChild(a);
	tweet.appendChild(document.createTextNode(", "));
	tweet.appendChild(document.createTextNode(response));
    } else {
        // Input mode
	url = '/cgi-bin/tweet';
	loadXMLDoc(url);
    }
}

function addMapMark(response,title) {
    var marks = document.getElementById('mapmarks');

    if (marks == null) {
	return;
    }

    if (response != '') {
	if (response != null) {
	    var localMarkers = [];
	    eval(response);
	    placeMapMarks(marks,localMarkers,title);
        }
    } else {
        // Input mode
	var clat = map.getCenter().lat();
	var clon = map.getCenter().lng();

	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();

	var minlat = southWest.lat();
	var minlng = southWest.lng();

	var maxlat = northEast.lat();
	var maxlng = northEast.lng();

	url = '/cgi-bin/mapmarks?lat=' + clat + '&long=' + clon + "&minlat=" + minlat + "&minlong=" + minlng + "&maxlat=" + maxlat + "&maxlong=" + maxlng;
	loadXMLDoc(url);
    }
}

window.onload = function(e) {
    setupNextLink('','');
    addpLinks();
    addSidebarClose();
    addTweet('','');
    addMapMark('','');
}

