// JavaScript Document
//Name: Alex Lei
//Date: 8/14/2005
//Js file for dynamically determine the menu options and validation of forms
//===============================================================================
//Table options
var tableItems = new Array("Electronic Resources (2001-)","Electronic Resources II (2001-)","Fiscal Support","Monographs-Additions","Total Volume Holdings","Other Materials Holdings","Personnel Support","Public Services","Serial Subscriptions & Non-purchased Serials","Acquisitions and Cataloging Form","Total Holdings and Unprocessed Backlog Materials","Total Holdings and Unprocessed Backlog Materials","Electronic Books");
var tableLink = new Array("viewelectronic.asp","viewelectronic2.asp","viewfiscalsupport.asp","viewmonographic.asp","viewvolumeholdings.asp","viewotherholdings.asp","viewpersonnelsupport.asp","viewpublicservice.asp","viewserial.asp","viewbacklog.asp","viewbacklog.asp","view_totalholdings.asp","viewelectronicbooks.asp");
var tableBit = new Array(1,1,2,1,2,2,2,1,2,0,1,0,1);
// -1 = unknown;0= old query only;1= new query only;2= mixed query
var determineQuery = -1;
var oldDetermineQuery = -1;


// function that deal with cookies...
//==========================================================================================

/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}


/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}
//=============================================================================
//get the array of values from an object 
function getSelectedIndexes(selObj) {
  if (selObj.type == 'select-one') {
         return new Array(selObj.selectedIndex);
  } else {
  var indexes = new Array();
  for (var i = 0; i < selObj.options.length; i++) {
      if (selObj.options[i].selected) {
           indexes.push(selObj.options[i].value);
       }
  }
  return indexes;
 }
}

//get the array of index from an object 
function getSelectedIndexes2(selObj) {
  if (selObj.type == 'select-one') {
         return new Array(selObj.selectedIndex);
  } else {
  var indexes = new Array();
  for (var i = 0; i < selObj.options.length; i++) {
      if (selObj.options[i].selected) {
           indexes.push(i);
       }
  }
  return indexes;
 }
}

//valid the form before submission
function validation()
{
	if (document.getElementById("cboYear").selectedIndex == 0)
	{
		alert ("Please select one or more year(s)!");
		return false;
	}
	else if (document.getElementById("cboTable").selectedIndex == 0)
	{
		alert ("Please select a table to be viewed!");
		return false;
	}
	else if (document.getElementById("cboLibrary").selectedIndex == -1)
	{
		alert("Please select one or more library(s)!");
		return false;
	}
	else
	{
		//save the option as cookie before return true
		//add the following code for that stupid IE problem ...
		setCookie("Table",frmView.cboTable.selectedIndex);
		//transfer the selected options to string
		var temp; 
		temp = getSelectedIndexes2(document.getElementById("cboLibrary"));
		temp1 = temp.toString();
		//set cookie for institution 
		setCookie("institution",temp1);
		
		//return to normal code...
		return true;
	}
}

//create XML requests
function GetXmlHttpObject(handler)
{ 
	var objXMLHttp=null
	if (window.XMLHttpRequest)
	{
		objXMLHttp=new XMLHttpRequest()
	}
	else if (window.ActiveXObject)
	{
		objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
	}
	return objXMLHttp
} 

// determine library list based on the year selection
function determineLib()
{
    if (document.getElementById("cboYear").value != "") {
	  var selectedIndex = new Array();
	  selectedIndex = getSelectedIndexes(document.getElementById("cboYear"));
	  oldDetermineQuery = determineQuery;
	  //determine if i cross the year query
	  if ((Number(selectedIndex[0]) >=1999) && (Number(selectedIndex[selectedIndex.length - 1]) >=1999)) {
	    determineQuery = 1;
	  }
	  if ((Number(selectedIndex[0]) <1999) && (Number(selectedIndex[selectedIndex.length - 1]) <1999)) {
	    determineQuery = 0;
	  }
	  if ((Number(selectedIndex[0]) >=1999) && (Number(selectedIndex[selectedIndex.length - 1]) <1999)) {
	    determineQuery = 2;
	  }
	  
	  if (oldDetermineQuery != determineQuery) {
	  //start sending request to determineLib.asp
	  var xmlHttp
	  xmlHttp = GetXmlHttpObject();
	  if (xmlHttp==null)
	  {
	  	alert("Browser does not support HTTP Request");
		return;
	  }
	  var temp,temp1;
	  temp = getSelectedIndexes(document.getElementById("cboLibrary"));
	  if (temp.toString() == '') {
	    temp1 = "null";
	  } else
	  {
	    temp1 = temp.toString();
	  }
	  var url = "determineLib.asp";
	  url = url + "?q=" + determineQuery;
	  url = url + "&s=" + temp1;
	  url=url+"&sid="+Math.random()
	  xmlHttp.onreadystatechange = stateChanged
	  document.getElementById("cboLibrary").disabled = true;
	  xmlHttp.open("GET",url,true);
	  xmlHttp.send(null);
	  }
	  //change the available table accordingly
	  determineTable();
	  //change the hidden value 
	  document.getElementById("cboDetermine").value = determineQuery;
	  
	  if (document.getElementById("btnSelectAll")) {
			document.getElementById("btnSelectAll").disabled = false;
	  }
	}
	
	function stateChanged() 
	{ 
		if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
		{ 
			//remove all the options
			var i;
			for (i=document.getElementById("cboLibrary").length-1;i>=0;i--)
			{
				document.getElementById("cboLibrary").options[i] = null;
			}	  
			document.getElementById("txtHint").innerHTML = xmlHttp.responseText;
			document.getElementById("cboLibrary").disabled = false;
		} 
	}
}

//determine what table i should show in the option
function determineTable()
{
   var temp1;
   if ((document.getElementById("cboTable").selectedIndex) == -1) {
	   document.getElementById("cboTable").options[0].selected = true
   } else
   {
   temp1 = document.getElementById("cboTable").options[document.getElementById("cboTable").selectedIndex].value
   }
   //remove all the options
   var i;
   for (i=document.getElementById("cboTable").length-1;i>=1;i--) {
			document.getElementById("cboTable").options[i] = null;
   }
   // add item back
   // only old is allowed
   if (determineQuery == 0) {
     var index = 1;
     for (i=0;i<tableItems.length;i++) {
	    //old and both table should show
     if ((tableBit[i] == 0) ||  (tableBit[i] == 2)) {
	   addOption(tableItems[i],tableLink[i],index,temp1);
	   index ++ ;
	   }
     }
   } else if (determineQuery == 1) {
      var index = 1;
     for (i=0;i<tableItems.length;i++) {
	    //old and both table should show
     if ((tableBit[i] == 1) ||  (tableBit[i] == 2)) {
	   addOption(tableItems[i],tableLink[i],index,temp1);
	   index ++ ;
	   }
     }

   } else if (determineQuery == 2) {
        var index = 1;
     for (i=0;i<tableItems.length;i++) {
	    //old and both table should show
     if ((tableBit[i] == 2)) {
	   addOption(tableItems[i],tableLink[i],index,temp1);
	   index ++ ;
	   }
     }

   } 
}

function addOption(name,value,index,selectIndexValue) {
  if (selectIndexValue == value)  {
   document.getElementById("cboTable").options[index] = new Option(name,value,true,true);
   } else {
   document.getElementById("cboTable").options[index] = new Option(name,value);
   }
}




//add the following code for IE problem ...
function init() 
{
	determineLib();
	//this is used to check if I the session is just started...
	//if (frmView.cboYear.selectedIndex != 0)
	if (document.getElementById("cboYear").selectedIndex != 0)
	{
		document.getElementById("cboTable").selectedIndex = getCookie("Table");
		/*var temp;
		var i;
		var j;
		temp = getCookie("institution");
		var temp2=temp.split(",");
		
		alert("hih");
		for (j = 0;j<temp2.length;j++) 
		{
			document.getElementById("cboLibrary").options[temp2[j]].selected = true;
		}
		*/
	}
}

window.onload = init;
