// holds an instance of XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();
// holds the remote server address and parameters
var serverAddress = "/modules/collections.xml";
// xmldoc returned by server
var xmlDoc = null;
// displays error messages if true
var debugMode = true;

var quest = "Welcome to the Quest Living Archive";

// creates an XMLHttpRequest instance
function createXmlHttpRequestObject() 
{
  // will store the reference to the XMLHttpRequest object
  var xmlHttp;
  // this should work for all browsers except IE
  try
  {
    // try to create XMLHttpRequest object
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    // assume IE7 or older
    var XmlHttpVersions = new Array("MSXML2.XMLHTTP.7.0",
    								"MSXML2.XMLHTTP.6.0",
                                    "MSXML2.XMLHTTP.5.0",
                                    "MSXML2.XMLHTTP.4.0",
                                    "MSXML2.XMLHTTP.3.0",
                                    "MSXML2.XMLHTTP",
                                    "Microsoft.XMLHTTP");
    // try every prog id until one works
    for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) 
    {
      try 
      { 
        // try to create XMLHttpRequest object
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      } 
      catch (e) {}
    }
  }
  // return the created object or display an error message
  if (!xmlHttp)
    alert("Error creating the XMLHttpRequest object.");
  else 
    return xmlHttp;
}

/*
// function that displays a new message on the page
function display(message)
{
  // obtain a reference to the <div> element on the page
  myDiv = document.getElementById("coll_display");
  
  // display message
  myDiv.innerHTML = message;
}

// function that displays an error message
function displayError(message)
{
  // display error message, with more technical details if debugMode is true
  display("Error retrieving the Collection! " +
          (debugMode ? message : ""));
}

function createQueryString()
{	
	// educator type
	var et = document.getElementsByName('educator_type[]');
	var etArr = new Array();
	for(a=0; a<et.length; a++) {
		if(et[a].checked)
			etArr.push(et[a].value);
	}
	var edType = "-1";
	if(etArr.length > 0) {
		edType = etArr.join("|");
	}
	
	// subject
	var su = document.getElementsByName('subject[]');
	var suArr = new Array();
	for(b=0; b<su.length; b++) {
		if(su[b].checked)
			suArr.push(su[b].value);
	}
	var sub = "-1";
	if(suArr.length > 0) {
		sub = suArr.join("|");
	}
	
	// build the query string
	var queryString = "";
	if(edType != "-1" && sub != "-1")
		queryString = "educator_type=" + edType + "&subject=" + sub;
	else if(edType != "-1" && sub == "-1")
		queryString = "educator_type=" + edType + "&subject=-1";
	else if(edType == "-1" && sub != "-1")
		queryString = "educator_type=-1" + "&subject=" + sub;

	return queryString;
}
*/

// call server asynchronously
function getCollXML()
{	
  // only continue if xmlHttp isn't void
  if (xmlHttp)
  {
    // try to connect to the server
    try
    {
      	// remove this line if you don't like the 'Loading...' message
		//display('<strong>' + 'Loading...' + '</strong>');
     	 // make asynchronous HTTP request to retrieve new message
		xmlHttp.open("GET", serverAddress, true);
		xmlHttp.onreadystatechange = handleGettingColl;
		xmlHttp.send(null);
    }
    catch(e)
    {
		displayError(e.toString());
    }
  }
}

/*
function js_array_to_php_array(a)
// This converts a javascript array to a string in PHP serialized format.
// This is useful for passing arrays to PHP. On the PHP side you can 
// unserialize this string from a cookie or request variable. For example,
// assuming you used javascript to set a cookie called "php_array"
// to the value of a javascript array then you can restore the cookie 
// from PHP like this:
//    <?php
//    session_start();
//    $my_array = unserialize(urldecode(stripslashes($_COOKIE['php_array'])));
//    print_r ($my_array);
//    ?>
// This automatically converts both keys and values to strings.
// The return string is not URL escaped, so you must call the
// Javascript "escape()" function before you pass this string to PHP.
{
    var a_php = "";
    var total = 0;
    for (var key in a)
    {
        ++ total;
        a_php = a_php + "s:" +
                String(key).length + ":\"" + String(key) + "\";s:" +
                String(a[key]).length + ":\"" + String(a[key]) + "\";";
                
        //display("<br /><br />" + a_php);
    }
    a_php = "a:" + total + ":{" + a_php + "}";
    
    //display("<br /><br />" + a_php);
    return a_php;
}
*/

// function called when the state of the HTTP request changes
function handleGettingColl() 
{
  // when readyState is 4, we are ready to read the server response
  if (xmlHttp.readyState == 4) 
  {
    // continue only if HTTP status is "OK"
    if (xmlHttp.status == 200) 
    {
      try
      {
        // do something with the response from the server
        xmlDoc = handleColl();
        
        // this is here to fix a bug
        collItemOpac(true);
      }
      catch(e)
      {
        // display error message
        displayError(e.toString());
        xmlDoc = null;
      }
    } 
    else
    {
      // display error message
      displayError(xmlHttp.statusText);   
    }
  }
}

// handles the response received from the server
function handleColl()
{
  // retrieve the server's response 
  var response = xmlHttp.responseXML;
  // server error?
  /*if (response.indexOf("ERRNO") >= 0 
      || response.indexOf("error") >= 0
      || response.length == 0)
    throw(response.length == 0 ? "Server error." : "Server error: " + response);
  */
  if(!response || response.length == 0)
	throw(response.length == 0 ? "Server error." : "Server error: " + response);
  
  
  return response;
}

function viewAll() {
	theForm = document.getElementsByTagName("form");
	for(i=0;i<theForm.length;i++) {
		// reference to the elements of the form
		c = theForm[i].elements;
		// loop over the length of those elements
		for(j=0;j<c.length;j++) {
			// if this element is a checkbox, do our thing
			if(c[j].getAttribute("type") == "checkbox") {
				c[j].checked=false;
			}
		}
	}
	
	collItemOpac(true);
	
	/*
	// restore the links
	var links = document.getElementsByTagName("a");
	for (var i=0; i<links.length; i++) {
    	if (links[i].getAttribute("class") == "coll_href") {
    		enableLink(links[i].getAttribute('id'));
      	}
	}
	*/

}

// function that displays an error message
function displayError(message)
{
  // display error message, with more technical details if debugMode is true
  display("Error retrieving the Collection! " +
          (debugMode ? message : ""));
}

function display(message)
{
  // obtain a reference to the <div> element on the page
  myDiv = document.getElementById("coll_display");
  
  // display message
  myDiv.innerHTML = message;
}

/*

Text/mouseover

*/
// The mouseover/mouseout functions
	
function overText(id, str1, str2, str3)
{

	document.getElementById(id).innerHTML = 
	'<strong>' + str1 + '</strong>' + '&nbsp;' + ' | ' + str2 + ' (' + str3 + ')';

	return true;
}

function outText(id)
{
	document.getElementById(id).innerHTML = " ";
	return true;
}

function collItemOpac(allOn) {
	if(allOn) {
		//turn all on
		doOpac(-1);
		return;
	}
	
	if(xmlDoc != null) {
		// form
		
		// educator type
		var et = document.getElementsByName('educator_type[]');
		var etVals = new Array();
		for(a=0; a<et.length; a++) {
			if(et[a].checked)
				etVals.push(et[a].value);
		}

		// subject
		var su = document.getElementsByName('subject[]');
		var suVals = new Array();
		for(b=0; b<su.length; b++) {
			if(su[b].checked)
				suVals.push(su[b].value);
		}
		
		// ====== generate list of 'on' images ======= //
		// xml doc
		var allItems = xmlDoc.getElementsByTagName("collectionitem");
		// associative array to hold the 'on' images
		var onList = new Object();
		// loop through all <collectionitem> tags
		for(i=0; i<allItems.length; i++) {
			var curr_id = allItems[i].getAttribute("id");
			// only one edlevel tag (with only one child node)
			var curr_edlevel = allItems[i].getElementsByTagName("edlevel")[0];
			// subjects
			var allSubjects = allItems[i].getElementsByTagName("subject");
			//document.write(subject[0].childNodes[0].nodeValue);
			// names
			var allNames = allItems[i].getElementsByTagName("name");
						
			// check whether or not any educator types were selected
			if(etVals.length > 0) {
				// loop through the selected educator types			
				for(j=0; j<etVals.length; j++) {
					// if there is a match
					if(curr_edlevel.childNodes[0].nodeValue.toString() == etVals[j]) {
						// ++++ add the image's id to the 'on' list ++++ //
						for(x=0; x<allNames.length; x++) {
							if(allNames[x].getAttribute("type") == "main") {
								var fname = allNames[x].getElementsByTagName("firstname")[0].childNodes[0].nodeValue;
								var lname = 				allNames[x].getElementsByTagName("lastname")[0].childNodes[0].nodeValue;
						onList[lname + '_' + fname + '_' + curr_id] = 'thumb_' + lname + '_' + fname + '_' + curr_id;
								break;
							}
						}
						// ++++ END add the image's id to the 'on' list ++++ //
					}
				} // END loop through the selected educator types			
				
				// check whether or not any subjects were selected
				if(suVals.length > 0) {
					// loop through the selected subjects
					var match = false;
					for(k=0; k<suVals.length; k++) {
						for(l=0; l<allSubjects.length; l++) {
							var curr_subjects = allSubjects[l].childNodes;
							for(m=0; m<curr_subjects.length; m++) {
								var curr_subject = curr_subjects[m].nodeValue;
								if(curr_subject == suVals[k]) {
									match = true;
									break;
								}
							}
						}
					} // END loop through the selected subjects (if there's a match)
					if(!match) {
						// ++++ remove the image's id from the 'on' list ++++ //
						for(y=0; y<allNames.length; y++) {
							if(allNames[y].getAttribute("type") == "main") {
								var fname = allNames[y].getElementsByTagName("firstname")[0].childNodes[0].nodeValue;
								var lname = 				allNames[y].getElementsByTagName("lastname")[0].childNodes[0].nodeValue;
								onList[lname + '_' + fname + '_' + curr_id] = -1;
								break;
							}
						}
					
					// ++++ END remove the image's id from the 'on' list ++++ //
					}
				} else { // no subjects selected
					//continue;
				/*
					for(jj=0; jj<etVals.length; jj++) {
						if(curr_edlevel.childNodes[0].nodeValue.toString() != etVals[jj]) {
							// ++++ remove the image's id from the 'on' list ++++ //
							var fname = 
							allItems[i].getElementsByTagName("firstname")[0].childNodes[0].nodeValue;
							var lname = 
							allItems[i].getElementsByTagName("lastname")[0].childNodes[0].nodeValue;
							if(!onList[lname + '_' + fname]) {
								onList[lname + '_' + fname] = -1;
							}
							// ++++ END remove the image's id from the 'on' list ++++ //
						}
					}*/
				}
			} else { // no educator types selected
				if(suVals.length > 0) { // only subject(s) were selected
					for(ll=0; ll<suVals.length; ll++) {
						for(lll=0; lll<allSubjects.length; lll++) {
							var curr_subjects = allSubjects[lll].childNodes;
							for(mm=0; mm<curr_subjects.length; mm++) {
								var curr_subject = curr_subjects[mm].nodeValue;
								// if there is a match
								if(curr_subject == suVals[ll]) {
									// ++++ add the image's id to the 'on' list ++++ //
									for(z=0; z<allNames.length; z++) {
										if(allNames[z].getAttribute("type") == "main") {
											var fname = allNames[z].getElementsByTagName("firstname")[0].childNodes[0].nodeValue;
											var lname = 				allNames[z].getElementsByTagName("lastname")[0].childNodes[0].nodeValue;
											onList[lname + '_' + fname + '_' + curr_id] = 'thumb_' + lname + '_' + fname + '_' + curr_id;
										break;
										}
									}
								}
							}
							// ++++ END add the image's id to the 'on' list ++++ 
						
						}
					}
				} else { // neither was selected
					onList = -1; // turn all on
				}
			}
		} // end outer for loop
		//display(String.split(onList));
		doOpac(onList);
	}
}

function doOpac(onImgList) {
	var allItems = xmlDoc.getElementsByTagName("collectionitem");
	
	if(onImgList == -1) {
		// all on
		for(i=0; i < allItems.length; i++) {
			var names = allItems[i].getElementsByTagName("names")[0];
			var allNames = names.getElementsByTagName("name");
			for(x=0; x<allNames.length; x++) {
				if(allNames[x].getAttribute("type") == "main") {
					var first_name = allNames[x].getElementsByTagName("firstname")[0].childNodes[0].nodeValue;
					var last_name = 				allNames[x].getElementsByTagName("lastname")[0].childNodes[0].nodeValue;
					var curr_id = allItems[i].getAttribute("id");
					var imgID = "thumb_" + last_name + "_" + first_name + "_" + curr_id;
					changeOpac(100, imgID);
					enableLink(last_name + '_' + first_name + '_' + curr_id);
					enableMouse(first_name, last_name, curr_id);
				}
			}
		}
		return;
	}
	
	var match = false;
	for(i=0; i < allItems.length; i++) {
		var first_name;
		var last_name;
		var names = allItems[i].getElementsByTagName("names")[0];
		var allNames = names.getElementsByTagName("name");
		var imgID;
		for(x=0; x<allNames.length; x++) {
			var curr_id = allItems[i].getAttribute("id");
			if(allNames[x].getAttribute("type") == "main") {
				first_name = allNames[x].getElementsByTagName("firstname")[0].childNodes[0].nodeValue;
				last_name = 				allNames[x].getElementsByTagName("lastname")[0].childNodes[0].nodeValue;
				imgID = "thumb_" + last_name + "_" + first_name + "_" + curr_id;
			}
		}
		
		for(id in onImgList ) {
			if(id==imgID) {
				var curr_id = allItems[i].getAttribute("id");
				// on stuff
				enableMouse(first_name, last_name, curr_id);
				enableLink(last_name + '_' + first_name + '_' + curr_id);
				//setCursorStyle(id, 'pointer');
				changeOpac(100, id);
				match = true;
				break;				
			}
		}
		if(!match) {
			var curr_id = allItems[i].getAttribute("id");
			if(onImgList[last_name + "_" + first_name + "_" + curr_id] == -1 || !onImgList[last_name + "_" + first_name + "_" + curr_id]) {
				// off stuff
				disableMouse(first_name, last_name, curr_id);
				disableLink(last_name + '_' + first_name + '_' + curr_id);
				//setCursorStyle(imgID, 'default');
				changeOpac(20, imgID);
			} else {
				enableMouse(first_name, last_name, curr_id);
				enableLink(last_name + '_' + first_name + '_' + curr_id);
				//setCursorStyle(imgID, 'pointer');
				changeOpac(100, imgID);
			}
		}
		match = false;
	} // end outer loop
	
}

function launchWin(urlToOpen) {
	newWindow=window.open(urlToOpen);
}

function enableLink(id) {
	var link = document.getElementById('link_' + id);
	link.onclick = function() {
     	launchWin(this.getAttribute("href"));
     	//self.status = " ";
      	return false;
    }

    /*
    link.onmouseover = function() {
    	self.status = " ";//this.getAttribute("href");
      	return true;
    }
    link.onmouseout = function() {
    	self.status = " ";
      	return true;
    }
    */

	// check for IE
	if (navigator.appVersion.indexOf("MSIE")==-1) {
		setCursorStyle('link_' + id, 'pointer');
	} else {
		setCursorStyle('link_' + id, 'hand');
	}
}

function disableLink(id) {

	var link = document.getElementById('link_' + id);
	link.onclick = function() {
		//self.status = " ";
      	return false;
    }

    /*
    link.onmouseover = function() {
    	self.status = " ";
      	return true;
    }
    link.onmouseout = function() {
    	self.status = " ";
      	return true;
    }
    */
    
    setCursorStyle('link_' + id, 'default');

}

function enableMouse(fname, lname, curr_id) {
	var id = "thumb_" + lname + "_" + fname + "_" + curr_id;
	var alt = document.getElementById(id).getAttribute("alt");
	var arr = alt.split("|");
	document.getElementById(id).onmouseover = function() {
		overText('coll_over_text', arr[0], arr[1] + ' ' + arr[2] + arr[3], arr[4]);
		fade_in_out(id, 250);
		return true;
	}
	document.getElementById(id).onmouseout = function() {
		outText('coll_over_text');
		changeOpac(100, id);
		return true;
	}
}

function disableMouse(fname, lname, curr_id) {
	var id = "thumb_" + lname + "_" + fname + "_" + curr_id;
	document.getElementById(id).onmouseover = function() {
		setStatus(quest);
		return true;
	}
	document.getElementById(id).onmouseout = function() {
		setStatus(quest);
		return true;
	}
}

function setStatus(x) {
	if(x == false)
		self.status = quest;
	else
		self.status = x;
		
	return true;
}

function selectOpac() {
	// determine which name was selected from pulldown list
	var sel = document.coll_form.teacher_name;
	var sel_name = sel.options[sel.selectedIndex].value;
	
	var allColls = xmlDoc.getElementsByTagName("collectionitem");
	
	var idx1 = sel_name.indexOf('_');
	var last_name = sel_name.substring(0, idx1-1);
	var idx2 = sel_name.lastIndexOf('_');
	var first_name = sel_name.substring(idx1+1, idx2-1);

	var last = sel_name.lastIndexOf('_');
	var idnum =  sel_name.substring(last+1, sel_name.length);
	//var final_name = sel_name;
	
	var onList = new Object();
	
	var name_count = 0;
	
	for(i=0; i<allColls.length; i++) {
		var names = allColls[i].getElementsByTagName("name");
		if(names.length > 1) {
			for(j=0; j<names.length; j++) {
				var curr_name = names[j];
				if(curr_name.getAttribute("type") == "extra" && curr_name.getAttribute("name_id") == idnum) {
					var main_fname = curr_name.getElementsByTagName("firstname")[0].getAttribute("main");
					var main_lname = curr_name.getElementsByTagName("lastname")[0].getAttribute("main");
					var objAttributes = allColls[i].attributes;
					var objRefAttr = objAttributes.getNamedItem("id");
					var realid = objRefAttr.nodeValue;
					var final_name = main_lname + "_" + main_fname + "_" + realid;
					onList[final_name] = 'thumb_' + final_name;
				} else if(allColls[i].getAttribute("id") == idnum) {
					var fname = curr_name.getElementsByTagName("firstname")[0].childNodes[0].nodeValue;
					var lname = curr_name.getElementsByTagName("lastname")[0].childNodes[0].nodeValue;
					var final_name = lname + "_" + fname + "_" + idnum;
					onList[final_name] = 'thumb_' + final_name;
				}
			}
		} else {
			for(k=0; k<names.length; k++) {
				var curr_name = names[k];
				var curr_fname = curr_name.getElementsByTagName("firstname")[0].childNodes[0].nodeValue;
				var curr_lname = curr_name.getElementsByTagName("lastname")[0].childNodes[0].nodeValue;
				if(sel_name.indexOf(curr_lname + "_" + curr_fname) != -1) {
					var curr_id = allColls[i].getAttribute("id");
					var final_name = curr_lname + "_" + curr_fname + "_" + curr_id;
					onList[final_name] = 'thumb_' + final_name;
				}
			}
		
		}
		
	}
	
	if(sel_name != "-1") {
		//var onList = new Object();
		//onList[final_name] = 'thumb_' + final_name;
		doOpac(onList);
	} else {
		//doOpac(-1);
		viewAll();
	}
}

/*
//form checkbox check/uncheck all
function CkAllNone() {
	theForm = document.getElementsByTagName("form");
	
	for(i=0;i<theForm.length;i++) {
		// reference to the elements of the form
		c = theForm[i].elements;
		// loop over the length of those elements
		for(j=0;j<c.length;j++) {
			// if this element is a checkbox, do our thing
			if(c[j].getAttribute("type") == "checkbox" && c[j].getAttribute("name") != "selectAll") {
				c[j].checked=theForm[i].elements["selectAll"].checked;
			}
		}
	}
}

function CkAll() {
    theForm = document.getElementsByTagName("form");
	
	for(i=0;i<theForm.length;i++) {
		// reference to the elements of the form
		c = theForm[i].elements;
		// loop over the length of those elements
		for(j=0;j<c.length;j++) {
			// if this element is a checkbox, do our thing
			if(c[j].getAttribute("type") == "checkbox" && c[j].getAttribute("name") == "selectAll") {
				theForm[i].elements["selectAll"].checked = true;
			}
		}
	}
	CkAllNone();
}
*/

