// this section from http://jibbering.com/2002/4/httprequest.html
// the search for compatibility!

var xmlHttp=false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
 try {
  xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (E) {
   xmlHttp = false;
  }
 }
@end @*/
if (!xmlHttp && typeof XMLHttpRequest!='undefined') {
	try {
		xmlHttp = new XMLHttpRequest();
	} catch (e) {
		xmlHttp=false;
	}
}
if (!xmlHttp && window.createRequest) {
	try {
		xmlHttp = window.createRequest();
	} catch (e) {
		xmlHttp=false;
	}
}
// at this point we pray that we have the necessary object.

var mothership = "/events/caption.php" ;

function create_form(name) {
	//create the form
	form = document.createElement("input") ;
	form.className = "borderless" ;

	// the first for IE, the second for everything else.
	form.onblur = call_mothership ;
	form.setAttribute("onBlur", 'call_mothership(this)') ;
	form.setAttribute("size", "15") ;

	// this should get us to the relevant span. . .
	var caption_target = name.parentNode ;
	caption_target.replaceChild(form, caption_target.firstChild) ;

	if(form.attachEvent) {
		form.attachEvent('blur', function() { call_mothership();}) ;
	}
}

function call_mothership(field) {
	// IE compatibility
	if(!field) {
		field = window.event.srcElement ;
	}
	// some tests
	var diag = 2 ;
	var newcaption = field.value ;
	var name = field.parentNode.previousSibling.getAttribute("href") ;
	if(newcaption != '') {
		diag = diag - 2 ;
	}
	if (diag == 0) {
		request = mothership + "?caption=" +
				escape(newcaption) + "&image=" + name + "" ;
		xmlHttp.open("GET", mothership + "?caption=" + 
				escape(newcaption) + "&image=" + name + 
				"", true) ;
		xmlHttp.onreadystatechange = manifest_caption ;
		xmlHttp.send(null) ;
	}
}

function manifest_caption() {
	if(xmlHttp.readyState == 4) {
		var response = xmlHttp.responseText ;
		// process response
		// TODO: respect second line of caption if necessary.
		var response_array = response.split('|') ;
		var caption = response_array[1] ;

		new_node = document.createTextNode(caption) ;
		// figure out where we need to put the new caption. . .
		links = document.getElementById("col2").
				getElementsByTagName("a") ;
		for (var i=0 ; i<links.length ; i++ ) {
			if(links[i].getAttribute("href") 
					== response_array[0]) {
				links[i].nextSibling.replaceChild(new_node, 
					links[i].nextSibling.firstChild ) ;
			}
		}

		// this holds until they, for whatever reason, reload
		// page.  consider setting a cookie so that they don't
		// see the form field again?

	}
}

