//START OF METHODS WRITTEN BY STEWART

// take id of record, return list of keywords for that record, each item a link to a new keyword search
function getKeywords(query, divId){
	//var ajaxURL = 'http://lettuce.tapor.uvic.ca/~siberian/scripts/getKeywords.php?id=' + query;
	var ajaxURL = '../scripts/getKeywords.php?id=' + query;
	var targEl = document.getElementById(divId);
	sendRequest(ajaxURL, null, 'GET', targEl, false, null);	
	//sendRequest(ajaxURL, null, 'GET', targEl, false, getLangOriginals(query, divId));	
}

function getLangOriginals(query, divId){
	//var ajaxURL2 = 'http://lettuce.tapor.uvic.ca/~siberian/scripts/getLangOriginals.php?id=' + query;
	var ajaxURL2 = '../scripts/getLangOriginals.php?id=' + query;
	var targEl2 = document.getElementById(divId);
	//alert('getLangOriginals query: ' + query + ' divId:' + divId);
	sendRequest(ajaxURL2, null, 'GET', targEl2, false, null);	
	//sendRequest(ajaxURL2, null, 'GET', targEl2, false,getJunk(query,divId));	
}

function getJunk(query,divId) {
	alert('getJunk query: ' + query + ' divId:' + divId);
	//getLangOriginals(query, divId);
}

function getElementsByClass( searchClass, domNode, tagName) {
	if (domNode == null) domNode = document;
	if (tagName == null) tagName = '*';
	var el = new Array();
	var tags = domNode.getElementsByTagName(tagName);
	var tcl = " "+searchClass+" ";
	for(i=0,j=0; i<tags.length; i++) {
		var test = " " + tags[i].className + " ";
		if (test.indexOf(tcl) != -1)
			el[j++] = tags[i];
	}
	return el;
}

function switch_language(new_language){
	
	//location of php file
	var url = 'scripts/switch_language.php?new_lang=' + new_language;

	if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}
	else {// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (xmlhttp) {
		xmlhttp.open("GET",url,false);
		xmlhttp.send(null);
		document.getElementById('ajax_container').innerHTML="SESSION[language] dynamically set to " + xmlhttp.responseText;
	} else { 
		alert ("NO xmlhttp object");
	}
	cur_language = new_language;
	display_language_elements(cur_language);
}

function display_language_elements(show_language) {
	
	var els_En = getElementsByClass('english');
	var els_Fr = getElementsByClass('french');
	var els_Ru = getElementsByClass('russian');
	if (show_language == 'french') {
		for(i=0; i<els_Ru.length; i++) {
			els_Ru[i].style.display = 'none';
	 	}
		for(i=0; i<els_En.length; i++) {
			els_En[i].style.display = 'none';
	 	}
		for(i=0; i<els_Fr.length; i++) {
			els_Fr[i].style.display = 'block';
	 	}
	} else if (show_language == 'russian') {
		for(i=0; i<els_Fr.length; i++) {
			els_Fr[i].style.display = 'none';
	 	}
		for(i=0; i<els_En.length; i++) {
			els_En[i].style.display = 'none';
	 	}
		for(i=0; i<els_Ru.length; i++) {
			els_Ru[i].style.display = 'block';
	 	}
	} else {
		for(i=0; i<els_Fr.length; i++) {
			els_Fr[i].style.display = 'none';
	 	}
		for(i=0; i<els_Ru.length; i++) {
			els_Ru[i].style.display = 'none';
	 	}
		for(i=0; i<els_En.length; i++) {
			els_En[i].style.display = 'block';
	 	}
	}
	
}

//END OF METHODS WRITTEN BY STEWART

//START OF LIBRARY FROM MARTIN

/* 
  Code for handling AJAX transactions. 
  This depends on the existence of a set of HTML elements
  in the page, looking like this:
  
  <div id="statusReport">
    <table id="progressBar">
      <tr id="progressBits">
        <td> </td>
      </tr>
    </table>
    <div id="statusText"> </div>
  </div>
  
  along with appropriate CSS for styling the elements.
*/


var req = null;
var READY_STATE_UNINITIALIZED = 0;
var READY_STATE_LOADING = 1;
var READY_STATE_LOADED = 2;
var READY_STATE_INTERACTIVE = 3;
var READY_STATE_COMPLETE = 4;
var currentlyWorking = false;
var ajaxTargetEl = null;
var ajaxReplaceTarget = false;
var funcToCallOnCompletion = null; //This function will be called, passing as a parameter the retrieved block of XHTML, if it's not null.

//Hardly any browsers seem able to handle this stuff properly, so we have to
//use innerHTML :-(
var badBrowser = (!document.importNode);
//var badBrowser = ((!document.importNode)||(navigator.userAgent.indexOf('Opera') > -1)||(navigator.userAgent.indexOf('Safari') > -1)||(navigator.userAgent.indexOf('Konqueror') > -1));

var msgDataNotFound = 'Unable to find the data requested.';
var msgDataNotUsable = 'Badly-formatted data returned from the database.';
var msgDoingSearch = 'Retrieving data...';
var msgInitializedReqObj = 'Initialized request object...';
var msgPreparingRequest = 'Preparing request...';
var msgAboutToSend = 'About to send...';
var msgSent = 'Request sent...';
var msgLoading = 'Loading...';
var msgComplete = 'Done!';

function sendRequest(url, params, HttpMethod, targEl, replaceTarget, funcToCall){
    if (targEl == null){ajaxTargetEl = null; return;}else{ajaxTargetEl = targEl;}
    ajaxReplaceTarget = replaceTarget;
    if (funcToCall != null){
      funcToCallOnCompletion = funcToCall;
    }
    else{
      funcToCallOnCompletion = null;
    }
    if (!HttpMethod){HttpMethod='GET';} //both post and get seem to work.
    startProgress(2, msgInitializedReqObj);
    req = initXMLHTTPRequest();
    if (req){
        stepProgress(3, msgPreparingRequest);
        req.onreadystatechange = onReadyState;
        req.open(HttpMethod, url, true);
        req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
        stepProgress(4, msgAboutToSend);
//        req.overrideMimeType('text/xml');
        if (HttpMethod == 'POST'){
          req.setRequestHeader("Content-length", params.length);
          req.setRequestHeader("Connection", "close");
        }
        req.send(params);
        stepProgress(5, msgSent);
    }
    else{
      setCursor('');
    }
}

function initXMLHTTPRequest(){
  stepProgress(2, 'Getting request object...');
  var xRequest = null;
  if (window.XMLHttpRequest){
    xRequest = new XMLHttpRequest();
  }
  else{
    if(window.ActiveXObject) {
      try {
        xRequest = new ActiveXObject('Msxml2.XMLHTTP');
      } 
      catch(e) {
        try {
          xRequest = new ActiveXObject('Microsoft.XMLHTTP');
        }
        catch(e) {
          xRequest = null;
        }
      }
    }
  }
  if (xRequest != null){   
    stepProgress(3, msgInitializedReqObj);
  }
  return xRequest;
}

function onReadyState(){
    var ready = req.readyState;
    if (ready == READY_STATE_COMPLETE){
      //setCursor(''); //commented out because it generates a js error
      stopStepDots();
      var Incoming = req.responseText;
	  //alert(Incoming);
      if ((Incoming.length < 4)||(req.responseXML == null)){
//We got no data from the Ajax request.
          //alert(Incoming.length);
          //alert(msgDataNotFound);
          //ajaxTargetEl.innerHTML = '';
      }
      else{
//We did receive some data.
        if (ajaxReplaceTarget == true){
//We're replacing the existing target node with the new content.
          if (document.importNode){
            var resultDoc = req.responseXML;
            if (resultDoc.childNodes.length < 1){
                //alert(msgDataNotFound);
                //ajaxTargetEl.innerHTML = '';
//Try non-standard stuff.
              ajaxTargetEl.outerHTML = Incoming;
            }
            else{
//alert('Removing target node');
              var resultNode = document.importNode(req.responseXML.childNodes[0], true);
              ajaxTargetEl.parentNode.replaceChild(resultNode, ajaxTargetEl);
            }
          }
          else{
//Try non-standard stuff for IE.
            ajaxTargetEl.outerHTML = Incoming;
          }
        }
        else{
//We're dropping the new content into the target node.
          if (document.importNode){
//			  alert('trying to import node.');
//Clean out the old content.
            for (var i=ajaxTargetEl.childNodes.length-1; i>=0; i--){
              ajaxTargetEl.removeChild(ajaxTargetEl.childNodes[i]);
            }
//Create a node from the incoming stuff.
            var resultDoc = req.responseXML;
            if (resultDoc.childNodes.length < 1){
//alert(msgDataNotFound);
//Try something non-standard, because this isn't working.
              ajaxTargetEl.innerHTML = Incoming;
            }
            else{
              var resultNode = document.importNode(req.responseXML.childNodes[0], true);
              ajaxTargetEl.appendChild(resultNode);
            }
          }
          else{
//Try non-standard stuff for IE.
            ajaxTargetEl.innerHTML = req.responseText;
          }

        }
      }
//Call the completion function if there is one.
      if (funcToCallOnCompletion != null){
        funcToCallOnCompletion(resultNode);
      }
      funcToCallOnCompletion = null;
      ajaxTargetEl = null;
      currentlyWorking = false;
      stepProgress(10, msgComplete);
    }//END OF READY_STATE_COMPLETE.
    else{
        stepProgress((ready + 5), msgLoading + '[' + ready + ']');
    }
}

function onReadyState_OLD(){
    var ready = req.readyState;
    if (ready == READY_STATE_COMPLETE){
        setCursor('');
        stopStepDots();
        var Incoming = req.responseText;
//alert(Incoming);
        if ((Incoming.length < 4)||(req.responseXML == null)){
            alert(msgDataNotFound);
            ajaxTargetEl.innerHTML = '';
        }
        else{
          if (ajaxReplaceTarget == true){
            var resultDoc = req.responseXML;
                if (resultDoc.childNodes.length < 1){
                    alert(msgDataNotFound);
                    ajaxTargetEl.innerHTML = '';
                }
                else{
//alert('Removing target node');
                    var resultNode = document.importNode(req.responseXML.childNodes[0], true);
                    ajaxTargetEl.parentNode.replaceChild(resultNode, ajaxTargetEl);
                    if (funcToCallOnCompletion != null){
                      funcToCallOnCompletion(resultNode);
                    }
                    funcToCallOnCompletion = null;
                }
          }
          else{
            for (var i=ajaxTargetEl.childNodes.length-1; i>=0; i--){
                ajaxTargetEl.removeChild(ajaxTargetEl.childNodes[i]);
            }
            if (badBrowser == true){
//alert(req.responseText);
//TODO: IE8 is choking here. My guess is that it's not able to set the innerHTML of a node that's 
//already been dynamically created.
                ajaxTargetEl.innerHTML = req.responseText;
                if (funcToCallOnCompletion != null){
                  funcToCallOnCompletion(ajaxTargetEl);
                }
                funcToCallOnCompletion = null;
            }
            else{
                var resultDoc = req.responseXML;
                if (resultDoc.childNodes.length < 1){
                    alert(msgDataNotFound);
                }
                else{
                    var resultNode = document.importNode(req.responseXML.childNodes[0], true);
                    ajaxTargetEl.appendChild(resultNode);
                    if (funcToCallOnCompletion != null){
                      funcToCallOnCompletion(resultNode);
                    }
                    funcToCallOnCompletion = null;
                }
            }
          }
        }
        ajaxTargetEl = null;
        currentlyWorking = false;
        stepProgress(10, msgComplete);
    }
    else{
        stepProgress((ready + 5), msgLoading + '[' + ready + ']');
    }
}

//var stepDots = '&#160;&#160;Waiting for results...';
var stepDots = 'Waiting for results...';
var curStepDots = stepDots;
var stepDotInterval = null;

function startStepDots(){
  curStepDots = stepDots;
  stepDotInterval = window.setInterval("showStepDots()", 2000);
}

function showStepDots(){
  if ((ajaxTargetEl != null)&&(ajaxReplaceTarget == false)){
    curStepDots += '.';
    ajaxTargetEl.innerHTML = '<span id="waiting">' + curStepDots + '</span>';
  }
}

function stopStepDots(){
  window.clearInterval(stepDotInterval);
}

function startProgress(numCells, report){
    startStepDots();
    //setCursor('wait'); //commented out because it generates a js error
    if (badBrowser){
        window.status = report;
        return;
    }
    var s = document.getElementById('statusReport');
    if (s != null){
        var t = null;
        var c = null;
        var progBits = document.getElementById('progressBits');
        if (progBits != null){
//Clear out previous progress cells
            for (var i=progBits.childNodes.length-1; i>=0; i--){progBits.removeChild(progBits.childNodes[i]);}
//Add new progress cells
            for (var i=0; i<numCells; i++){
                t = document.createTextNode(' ');
                c = document.createElement('td');
                c.appendChild(t);
                progBits.appendChild(c);
            }  
        }
        s.style.display = 'block';
        stepProgress(1, report);
    }
}

function stepProgress(step, report){
//alert('Stepping progress: step ' + step + '; report: ' + report);
    showStepDots();
    if (badBrowser){
        window.status = report;
        return;
    }
    var progBits = document.getElementById('progressBits');
    if (progBits != null){
        var stat = document.getElementById('statusText');
        if (stat != null){
//Remove previous message
            for (var i=stat.childNodes.length-1; i>=0; i--){stat.removeChild(stat.childNodes[i]);}
//Add new message
            var t = document.createTextNode(report);
            stat.appendChild(t);
        }
//Fill in the td elements to show progress
        for (var i=0; i<step; i++){
            if (progBits.getElementsByTagName('td').length > i){
                if (progBits.getElementsByTagName('td')[i] != null){
                    progBits.getElementsByTagName('td')[i].setAttribute('class', 'stepped');
                }
            }
        }
        if (step == progBits.getElementsByTagName('td').length){
            window.setTimeout('document.getElementById("statusReport").style.display = "none"', 1000);
        }
    }
}
//END OF LIBRARY FROM MARTIN


//START OF METHODS FROM BEN

var newwindow;

/* original version of function, caused calling page to be replaced with 'false'
rest of these methods had same 2 lines of code, which I removed */
/*
function windowquery(url)
{
	newwindow=window.open(url,'name', 'height=800,width=1024,left=20,top=20');
	if (window.focus) {newwindow.focus()}
	void(0);
	return false;
}
*/
/*working version, calling page is now left alone*/
function windowquery(url)
{
	newwindow=window.open(url,'name', 'height=800,width=1024,left=20,top=20');
	if (window.focus) {newwindow.focus()}
}

function windowsource(url)
{	
	newwindow=window.open(url,'name','height=600,width=600,left=20,top=20');
	if (window.focus) {newwindow.focus()}
}

function windowphoto(url)
{	
	newwindow=window.open(url,'name','height=600,width=600,left=20,top=20');
	if (window.focus) {newwindow.focus()}
}


function windowwide(url)
{
	newwindow=window.open(url,'name','height=600,width=900,left=20,top=20');
	if (window.focus) {newwindow.focus()}
}

function windowwidest(url)
{
	newwindow=window.open(url,'name','height=600,width=1000,left=20,top=20');
	if (window.focus) {newwindow.focus()}
}

function windowshallow(url)
{
	newwindow=window.open(url,'name','height=200,width=600,left=20,top=20');
	if (window.focus) {newwindow.focus()}
}

function windowaudio(url)
{
	newwindow=window.open(url,'name','height=200,width=600,left=20,top=20');
	if (window.focus) {newwindow.focus()}
}

function windowvideo(url)
{
	newwindow=window.open(url,'name','height=400,width=600,left=20,top=20');
	if (window.focus) {newwindow.focus()}
}

function windowcustom1(url)
{
	newwindow=window.open(url,'name','height=420,width=520,left=20,top=20');
	if (window.focus) {newwindow.focus()}
}

function windowmap(url)
{
	newwindow=window.open(url,'name','height=600,width=900,left=20,top=20');
	if (window.focus) {newwindow.focus()}
}

