//
// Cicada Dictionary Assistant (c) 2006 by Edward H. Trager.  All Rights Reserved
//
//

//
// NOTE BENE: HARD CODED URL IN THE CODE HERE:
//
// In order to have the javascript load links using the assistant,
// we need to know the assistant's base URL:
//
var cicadaAssistantURL="http://eyegene.ophthy.med.umich.edu/assist/index.php";

//
// Global to track the selection:
//
var lastSelection="";

//
// This sets up so we can drag the Cicada assistant window:
// Also allows to follow links using the Cicada assistant:
//
document.onmousedown   = mouseDownEventHandler;

//
// This sets up shading (roll up) of the Cicada assistant window,
// 
// --> But this is still broken for several reasons, so comment out:
//
//document.ondblclick = shadeWindow;

//
// Several different event handling possibilities exist 
// on mouseUp call. What is really needed is to capture the
// object and use the correct event handler for each object.
// But the following is good enough for the proof-of-concept
// code:
//
// 1) Call getUserSelection() whenever the mouse goes up:
// 2) Also call setDraggableToFalse whenever mouse goes up:
//
window.onmouseup=mouseUpEventHandler;

//
// mouseUpEventHandler()
//
function mouseUpEventHandler(){
	
	setDraggableToFalse();
	getUserSelection();

}


//
// getUserSelection()
//
// --> Gets the text highlighted by the user
//
function getUserSelection(){
	
	var selection;
	selection=String(window.getSelection());
	if(selection.length){
		
		if(selection!=lastSelection){
			
			lastSelection=selection;
			loadXMLDocument('search.php');

		}
	}
	
}

//
// global XML HTTP Request object:
//
var request=false;

//
// Global state "constants":
//
var REQUEST_IS_UNINITIALIZED = 0;
var REQUEST_IS_LOADING       = 1;
var REQUEST_IS_LOADED        = 2;
var REQUEST_IS_INTERACTIVE   = 3;
var REQUEST_IS_COMPLETE      = 4;
var REQUEST_STATUS_IS_OK     = 200;


//
// loadXMLDocument()
//
// -> Loads XML documents using XMLHttpRequest.
// -> If one document is already in the middle of being processed,
//    new requests are pushed onto a pending stack.
// -> Pending requests on the stack are later popped by the processChangeRequest()
//    method as soon as processing of the prior document is complete.
// 
function loadXMLDocument(URL){
	//
	// If request already exists, that means a document is in the middle of
	// being processed, so we push all subsequent URLs onto a stack:
	//
	
	request=false;
	
	if(window.XMLHttpRequest){
		try{
			request = new XMLHttpRequest;
		}catch(e){
			request = false;
		}
	}else if(window.ActiveXObject){
		try{
			request = new ActiveXObject("Mxml2.XMLHTTP");
		}catch(e){
			try{
				request = new ActiveXObject("Microsoft.XMLHTTP");
			}catch(e){
				request = false;
			}
		}
	}
	if(request){
		
		request.onreadystatechange = processRequestChange;
		request.open("POST",URL,true);
		request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		//
		// Sending the query string via POST :
		//	
		request.send("queryString="+lastSelection);
		
	}
}


//
// processRequestChange()
//
function processRequestChange(){
	
	// Only process if request show "loaded":
	if(request.readyState == REQUEST_IS_COMPLETE){
		// Only if "OK":
		if(request.status==REQUEST_STATUS_IS_OK){
			// Process entry nodes:
			populatePage();
			
		}else{
			alert("Unable to load XML data: "+request.statusText);
		}
	}
}

//
// populatePage() : Populate the Cicada Assistant result window
//
function populatePage(){
	
	var entryCount = request.responseXML.getElementsByTagName("entry").length;
	var simplified,traditional,pinyin,zhuyin,definition,example,illustration;
	var s,t,p,z,d,e,j;
	
	OutputString="";
	
	for(var i=0;i<entryCount;i++){
		
		s=request.responseXML.getElementsByTagName("entry")[i].getElementsByTagName('s')[0].firstChild;
		simplified = s ? s.nodeValue:"";
		t=request.responseXML.getElementsByTagName("entry")[i].getElementsByTagName('t')[0].firstChild;
		traditional= t ? t.nodeValue:"";
		p=request.responseXML.getElementsByTagName("entry")[i].getElementsByTagName('p')[0].firstChild;
		pinyin     = p ? p.nodeValue:"";
		z=request.responseXML.getElementsByTagName("entry")[i].getElementsByTagName('z')[0].firstChild;
		zhuyin     = z ? z.nodeValue:"";
		d=request.responseXML.getElementsByTagName("entry")[i].getElementsByTagName('d')[0].firstChild;
		definition = d ? d.nodeValue:"";
		e=request.responseXML.getElementsByTagName("entry")[i].getElementsByTagName('e')[0].firstChild;
		example    = e ? e.nodeValue:"";
		j=request.responseXML.getElementsByTagName("entry")[i].getElementsByTagName('i')[0].firstChild;
		illustration= j ? j.nodeValue:"";
		
		var entry    = "<div class='entry'><div class='zi'>";
		entry       += "<div class='s'>"+simplified+"</div><div class='t'>"+traditional+"</div>";
		entry       += "</div>\n";
		entry       += "<div class='p'>"+pinyin+"</div><div class='z'>"+zhuyin+"</div>";
		entry       += "<div class='d'>"+definition+"</div>";
		entry       += "<div class='e'>"+example+"</div>";
		if(j){
			entry       += "<img src='illustrations/"+illustration+"' alt='i' width='40' />";
		}
		entry+="</div>\n";
		
		OutputString+=entry;
	}
	
	document.getElementById("resultSet").innerHTML=OutputString;
	
}

//
// WINDOW ACTION STUFF (culled from windowActions.js):
//

var mouseStartX;
var mouseStartY;
var objectStartX;
var objectStartY;

var isDraggable=false;
var draggableObject;


//
// setDraggableToFalse()
//
function setDraggableToFalse(){
	
	isDraggable=false;
	
}

//
// mouseDownEventHandler()
//
function mouseDownEventHandler(e){

	var fobj = getTargetElement(e);
	
	if(fobj.tagName=='A'){
		
		handleLink(fobj);

	}else{

		grabWindow(fobj,e);

	}
}

//
// handleLink()
//
function handleLink(fobj){
	
	if(confirm("Load link "+fobj.href+" using Cicada assistant?")){
		
		document.location=cicadaAssistantURL+"?requestURL="+fobj.href;
	}else{
		document.location=fobj.href;
	}
	return false;
}

window.captureEvents(Event.CLICK);
window.onclick = processClicks;

//
// Don't let browser load links, only our JS can do it:
//
function processClicks(e){

	var fobj = getTargetElement(e);
	if(fobj.tagName=='A'){
		e.preventDefault();
		return false;
	}else{
		return true;
	}
}
	
//
// function grabWindow
//
function grabWindow(fobj,e){
	
	var topElement = "HTML";
	
	// 
	// recurse up parent nodes looking for a "windowTitleBar" object:
	//
	while(fobj.tagName!=topElement && fobj.className!="windowTitleBar"){
		
		fobj=fobj.parentNode;
		
	}
	
	if(fobj.tagName!=topElement){
		//
		// We actually want to drag the window title bar's parent, 
		// which is the window container itself:
		// 
		fobj = fobj.parentNode;
		
		isDraggable=true;
		draggableObject=fobj;
		//
		// Fix up top and left if they are not set:
		//
		// ROUGH SPOT : IS THIS GECKO-SPECIFIC ?
		//
		if(!draggableObject.style.left){
			draggableObject.style.left = document.defaultView.getComputedStyle(draggableObject,'').getPropertyValue('left');
		}
		if(!draggableObject.style.top){
			draggableObject.style.top = document.defaultView.getComputedStyle(draggableObject,'').getPropertyValue('top');
		}
		
		//alert(document.defaultView.getComputedStyle(draggableObject,'').getPropertyValue('top'));
		//return;
		objectStartX = parseInt(draggableObject.style.left+0);
		objectStartY = parseInt(draggableObject.style.top+0);
		mouseStartX  = e.clientX;
		mouseStartY  = e.clientY;
		// Set the move handler:
		document.onmousemove=moveObject;
	}
}

//
// moveObject()
//
function moveObject(e){
	
	if(isDraggable){
		
		var newX = objectStartX + e.clientX - mouseStartX ;
		var newY = objectStartY + e.clientY - mouseStartY ;
		draggableObject.style.left=newX+"px";
		draggableObject.style.top =newY+"px";
		
	}
	return false;
	
}

//
// function shadeWindow()
//
function shadeWindow(e){
	
	var fobj = getTargetElement(e);
	
	var topElement = "HTML";
	
	// 
	// recurse up parent nodes looking for a "windowTitleBar" object:
	//
	while(fobj.tagName!=topElement && fobj.className!="windowTitleBar"){
		
		fobj=fobj.parentNode;
		
	}
	
	if(fobj.tagName!=topElement){
		//
		// Go to the parent which is the actual window itself:
		//
		fobj = fobj.parentNode;
		
		//
		// Look for the "windowCanvas" child:
		//
		var i;
		var child=false;
		for(i=0;i<fobj.childNodes.length;i++){
			
			if(fobj.childNodes[i].className=="windowCanvas"){
				child=fobj.childNodes[i];
				if(child.style.display=="none"){
					child.style.display="block";
				}else{
					child.style.display="none";
				}
				return;
				
			}
		}
		
	}
	
}


//
// captureMouseCoordinates
//
//function captureMouseCoordinates(e){
//	
//	if(document.all){
//		// IE:
//		mouseX = window.event.x + document.body.scrollLeft;
//		mouseY = window.event.y + document.body.scrollTop;
//	}else{
//		// W3C DOM:
//		mouseX=e.pageX;
//		mouseY=e.pageY;
//	}
//}

//
// getTargetElement() -- CROSS-BROWSER-OK
//
function getTargetElement(evt) {
	
	var elem;
	
	if (evt.target) {
		elem = (evt.target.nodeType == 3) ? evt.target.parentNode : evt.target;
	} else {
		elem = evt.srcElement;
	}
	return elem;
	
}


