/*
#(c)#=====================================================================
#(c)#
#(c)#       Copyright 2007 ExLibris Group
#(c)#                       All Rights Reserved
#(c)#
#(c)#=====================================================================

**          Product : WebVoyage :: ajaxUtils js
**          Version : 7.0
**          Created : 26-MAR-2007
**      Orig Author : Mel Pemble
**    Last Modified : 04-JUN-2008
** Last Modified By : Mel Pemble
*/

var httpRequest = null;
var validForm ="false";
var validationErrorMsg ="";
var state = 'none';
var scheduleChecked = 'false';


// Create the Divtag Handler -- Mainly an IE 6 Fix
var divhandler = new handleDivTag(null);

//////////////////////////////////////////////////////////////////////

function createXMLHttpRequest()
{
   /* In most browsers, XMLHttpRequest is a standard Javascript class,
   ** so you just create a new instance XMLHttpRequest. However, Microsoft
   ** were the inventors of XMLHttpRequest, and until IE7, IE only offered
   ** as an ActiveX object. To make things even more fun, there are different
   ** versions of that object. The following code shows a factory function
   ** that works on all browsers that support XMLHttpRequest.
   */

   // branch for IE/Windows ActiveX version
   try
   {
      return new ActiveXObject("Msxml2.XMLHTTP");
   } catch (e) {}

   try
   {
      return new ActiveXObject("Microsoft.XMLHTTP");
   } catch (e) {}

   // branch for native XMLHttpRequest object
   try
   {
      return new XMLHttpRequest();
   } catch(e) {}

   alert("Problem creating the XMLHttpRequest object. \nPlease use a XMLHttpRequest/AJAX capable browser.\n\n                 For Help, contact support.");

   return null;
}

//////////////////////////////////////////////////////////////////////

function handleDivTag(divtag)
{
   var divtag;
   return divtag;
}

//////////////////////////////////////////////////////////////////////

function getRequests(bibId,mfhdAttrs,bibDbCode,divtag)
{

    var send = "getRequests?bibId="+bibId;
        if(mfhdAttrs) {send += '&mfhds='+mfhdAttrs};
        if(bibDbCode) {send += '&bibDbCode='+bibDbCode};

   divhandler.divtag = divtag;

    httpRequest = createXMLHttpRequest();
    if (httpRequest != null)
    {
        if (httpRequest.overrideMimeType)
        {
            httpRequest.overrideMimeType('text/xml');
        }
        httpRequest.open("GET", send, true);
        httpRequest.onreadystatechange = handleRequestsResponse;
        httpRequest.send(null);
    }
}

//////////////////////////////////////////////////////////////////////

function handleRequestsResponse()
{
//   if(httpRequest.readyState == 0) { document.getElementById(divhandler.divtag).innerHTML = 'Creating Request Object...'; }
//   if(httpRequest.readyState == 1) { document.getElementById(divhandler.divtag).innerHTML = 'Loading Request Object...'; }
//   if(httpRequest.readyState == 2) { document.getElementById(divhandler.divtag).innerHTML = 'Request Object Loaded! Sending....'; }
//   if(httpRequest.readyState == 3) { document.getElementById(divhandler.divtag).innerHTML = 'Receiving getRequests Data....'; }
   if(httpRequest.readyState == 4) 
   { 
//      document.getElementById(divhandler.divtag).innerHTML = 'Displaying Data....';
      if(httpRequest.status == 200)
      {
         // Text returned FROM the servlet
         var response = httpRequest.responseText;

         if(response)
         {
            // UPDATE content
            document.getElementById(divhandler.divtag).innerHTML = response;
         }
      }
      else if(httpRequest.status == 500)
      {


         document.getElementById(divhandler.divtag).innerHTML = '<a href="#" onclick="errorWindow.show();">!!! Error !!!</a>';
         errorWindow = new Window({id: "errWin",className: "alphacube", title: "!!! Error !!!", width:200, height:150, top:70, left:100}); errorWindow.getContent().innerHTML = httpRequest.responseText;
         WindowStore.init();
      }
      else
      {
         document.getElementById(divhandler.divtag).innerHTML = '!!! Communications Error !!!';
      }
   }
}

///////////////////////////////////////////////////////////////////////

function getRequestPage(urlStr,bibID,mfhdAttrs,bibDbCode,bibDbName)
{

   var reqURL = "getRequest?"+urlStr;
        reqURL += "&bibId="+bibID;
        reqURL += "&mfhds="+mfhdAttrs;
        if(bibDbCode) {reqURL += '&bibDbCode='+bibDbCode};
        if(bibDbName) {reqURL += '&bibDbName='+bibDbName};

    window.location.href=reqURL;
}

//////////////////////////////////////////////////////////////////////

function getSLDates(requestSiteId,bibId,itemId,SL_Res_Date)
{

    var send = "getShortLoanDates?requestSiteId="+requestSiteId;
        if(bibId)  {send += '&bibId=' +bibId};
        if(itemId) {send += '&itemId='+itemId};
        if(SL_Res_Date) {send += '&SL_Res_Date='+SL_Res_Date};

    httpRequest = createXMLHttpRequest();

    if (httpRequest != null)
    {
        if (httpRequest.overrideMimeType)
        {
            httpRequest.overrideMimeType('text/xml');
        }
        httpRequest.open("GET", send, true);
        httpRequest.onreadystatechange = handleSLDateResponse;
        httpRequest.send(null);
    }
}

///////////////////////////////////////////////////////////////////////

function handleSLDateResponse()
{
   if(httpRequest.readyState == 4 && httpRequest.status == 200)
   {
      // Text returned FROM the servlet
      var response = httpRequest.responseXML;

      if(response)
      {
         // UPDATE content
         populateReservationDates();
      }
   }
}

///////////////////////////////////////////////////////////////////////

function handleChangeUBHoldingsLibResponse()
{
   if(httpRequest.readyState == 4 && httpRequest.status == 200)
   {
      // Text returned FROM the servlet
      var response = httpRequest.responseXML;

      if(response)
      {
         // UPDATE content
         populateUBDropDown('copies','itemId');
         populateUBDropDown('pickUpLibraries','Select_Pickup_Lib');
         populateUBDropDown('pickUpLocations','PICK');

      }
   }
}

///////////////////////////////////////////////////////////////////////

function handleChangePickupLibResponse()
{
   if(httpRequest.readyState == 4 && httpRequest.status == 200)
   {
      // Text returned FROM the servlet
      var response = httpRequest.responseXML;

      if(response)
      {
         // UPDATE content
         populateUBDropDown('pickUpLocations','PICK');

      }
   }
}

///////////////////////////////////////////////////////////////////////

function populateReservationDates()
{
   var resDateDropDown = document.getElementById('SL_Res_Date');
       resDateDropDown.options.length = 0;

   var xml = httpRequest.responseXML;       // grab the xml from the DOM

   var startDates=getTagName(xml,"startDate");

   for (iEle=0;iEle<startDates.length;iEle++)
   {
      node = startDates[iEle];

      isSelected = matchAttribute(node,'isSelected');
      displayTime= matchAttribute(node,'displayTime');
      serverTime = matchAttribute(node,'serverTime');
      resDateDropDown.options[resDateDropDown.options.length] = new Option(displayTime,serverTime);
      if(isSelected=="Y")
      {
         resDateDropDown.options[resDateDropDown.options.length-1].selected = "selected";
      }
   }
   populateStartTimes();
}

///////////////////////////////////////////////////////////////////////

function populateStartTimes()
{
   var resDateDropDown = document.getElementById('SL_Res_Date');
   var timeDropDown = document.getElementById('SL_Start_Time');

       timeDropDown.options.length = 0;

   var xml = httpRequest.responseXML;       // grab the xml from the DOM

   var startDates=getTagName(xml,"startDate");

   for (iEle=0;iEle<startDates.length;iEle++)
   {
      node = startDates[iEle];

      serverTime = matchAttribute(node,'serverTime');

      if (serverTime == resDateDropDown.options[resDateDropDown.options.selectedIndex].value)
      {
         for (iTimes=0;iTimes<startDates[iEle].childNodes.length;++iTimes)
         {
            timeNode = startDates[iEle].childNodes[iTimes];
            isSelected = matchAttribute(timeNode,'isSelected');
            displayTime= matchAttribute(timeNode,'displayTime');
            serverTime = matchAttribute(timeNode,'serverTime');
            timeDropDown.options[timeDropDown.options.length] = new Option(displayTime,serverTime);
            if(isSelected=="Y")
            {
               timeDropDown.options[timeDropDown.options.length-1].selected = "selected";
            }
         }
      }
   }
   populateEndTimes();
}

///////////////////////////////////////////////////////////////////////

function populateEndTimes()
{
   var resDateDropDown   = document.getElementById('SL_Res_Date');
   var startTimeDropDown = document.getElementById('SL_Start_Time');
   var endTimeDropDown   = document.getElementById('endtimes');
       endTimeDropDown.options.length = 0;

   if(startTimeDropDown.options.selectedIndex < 0)
   {
      return false;
   }
   var xml = httpRequest.responseXML;       // grab the xml from the DOM

   var startDates=getTagName(xml,"startDate");

   for (iEle=0;iEle<startDates.length;iEle++)
   {
      node = startDates[iEle];

      dateServerTime = matchAttribute(node,'serverTime');

      if (dateServerTime == resDateDropDown.options[resDateDropDown.options.selectedIndex].value)
      {
         for (iStartTimes=0;iStartTimes<startDates[iEle].childNodes.length;++iStartTimes)
         {
            startTimeNode   = startDates[iEle].childNodes[iStartTimes];
            startServerTime = matchAttribute(startTimeNode,'serverTime');
            if(startServerTime == startTimeDropDown.options[startTimeDropDown.options.selectedIndex].value)
            {
               for (iEndTimes=0;iEndTimes<startDates[iEle].childNodes[iStartTimes].childNodes.length;++iEndTimes)
               {
                  endTimeNode = startDates[iEle].childNodes[iStartTimes].childNodes[iEndTimes];

                  isSelected = matchAttribute(endTimeNode,'isSelected');
                  displayTime= matchAttribute(endTimeNode,'displayTime');
                  serverTime = matchAttribute(endTimeNode,'serverTime');

                  endTimeDropDown.options[endTimeDropDown.options.length] = new Option(displayTime,serverTime);
                  if(isSelected=="Y")
                  {
                     endTimeDropDown.options[endTimeDropDown.options.length-1].selected = "selected";
                  }
               }
            }
         }
      }
   }

}

///////////////////////////////////////////////////////////////////////

function slLoad(requestSiteId,bibId)
{

   var copy = document.getElementById('itemId').options[document.getElementById('itemId').options.selectedIndex].value;
   var serverTime = document.getElementById('SL_Res_Date').options[document.getElementById('SL_Res_Date').options.selectedIndex].value;

   getSLDates(requestSiteId,bibId,copy,serverTime);

}

////////////////////////////////////////////////////////////////////////

function changeUBHoldingsLib(selLib,bibId)
{

    var send = "changeUBHoldingsLib?Select_Library="+selLib;
        if(bibId)  {send += '&bibId=' +bibId};

    httpRequest = createXMLHttpRequest();

    if (httpRequest != null)
    {
        if (httpRequest.overrideMimeType)
        {
            httpRequest.overrideMimeType('text/xml');
        }
        httpRequest.open("GET", send, true);
        httpRequest.onreadystatechange = handleChangeUBHoldingsLibResponse;
        httpRequest.send(null);
    }
}

////////////////////////////////////////////////////////////////////////

function changeUBPickUpLib(selPuLib)
{
    var selLib = document.getElementById('Select_Library').options[document.getElementById('Select_Library').options.selectedIndex].value;
    var send = "changeUBPickupLib?Select_Pickup_Lib="+selPuLib;
    if(selLib)  {send += "&Select_Library="+selLib}

    httpRequest = createXMLHttpRequest();

    if (httpRequest != null)
    {
        if (httpRequest.overrideMimeType)
        {
            httpRequest.overrideMimeType('text/xml');
        }
        httpRequest.open("GET", send, true);
        httpRequest.onreadystatechange = handleChangePickupLibResponse;
        httpRequest.send(null);
    }
}

////////////////////////////////////////////////////////////////////////
// reqNodeName - this is the name of the node in the responseText XML //
//               in which to grab the data from                       //
// ddId        - this is the id of the dropDown in html where to put  //
//               the new values found in the XML                      //
////////////////////////////////////////////////////////////////////////

function populateUBDropDown(reqNodeName,ddId)
{
   var myDropDown = document.getElementById(ddId);    // use DOM to get to our dropdown
       myDropDown.options.length = 0;                 // clear out the old values

   var xml = httpRequest.responseXML;                 // grab the xml from the xml response

   var eleNode=getTagName(xml,reqNodeName);           // parse thru the responseXML to the requested node name

   // Loop thru the child elements of the parent node and build our dropDown data
   for (iEle=0;iEle<eleNode[0].childNodes.length;iEle++)
   {
      node = eleNode[0].childNodes[iEle];             // copy the node structure

      // assign the values
       isDefault = matchAttribute(node,'isDefault');
           idVal = matchAttribute(node,'id');
      displayVal = eleNode[0].childNodes[iEle].firstChild.nodeValue;

      // insert the values into the dropdown
      myDropDown.options[myDropDown.options.length] = new Option(displayVal,idVal);

      // default selection check
      if(isDefault=="Y")
      {
         myDropDown.options[myDropDown.options.length-1].selected = "selected";
      }
   }
}

////////////////////////////////////////////////////////////////////////

function matchAttribute(node,matchtext)
{
   for(iAttr=0;iAttr<node.attributes.length;iAttr++)
   {
      if (node.attributes[iAttr].nodeName == matchtext)
      {
         var nodVal = node.attributes[iAttr].nodeValue;
         return nodVal;
      }
   }
   return;
}

////////////////////////////////////////////////////////////////////////

function changeMediaItem()
{
   validForm ="true";
   validationErrorMsg = "";

   var send = "changeMediaItem?";
       send += buildItems();

//       alert(send);
   if (validForm == "true")
   {
       httpRequest = createXMLHttpRequest();

       if (httpRequest != null)
       {
           if (httpRequest.overrideMimeType)
           {
               httpRequest.overrideMimeType('text/xml');
           }
           httpRequest.open("GET", send, true);
           httpRequest.onreadystatechange = handleChangeMediaItem;
           httpRequest.send(null);
       }
   }
   else if (validForm == "false")
   {
      alert(validationErrorMsg);
   }

}

////////////////////////////////////////////////////////////////////////

function validateItemReq()
{
   validForm ="true";
   validationErrorMsg = "";

   var send = "validateMediaItem?";
       send += buildItems();
       send += buildCheckoutTimes();
       send += buildMediaPickOrDeliver();
       send += "&";
       send += buildEquipTypes();
       send += validateHiddenProps();


//       alert(send);
   if (validForm == "true")
   {
       httpRequest = createXMLHttpRequest();

       if (httpRequest != null)
       {
           if (httpRequest.overrideMimeType)
           {
               httpRequest.overrideMimeType('text/xml');
           }
           httpRequest.open("GET", send, true);
           httpRequest.onreadystatechange = handleValidateMediaEquip;
           httpRequest.send(null);
       }
   }
   else if (validForm == "false")
   {
      alert(validationErrorMsg);
   }
}

////////////////////////////////////////////////////////////////////////

function validateMediaEquip()
{
   validForm ="true";
   validationErrorMsg = "";

   var send = "validateMediaEquipment?";
       send += buildEquipTypes();
       send += buildCheckoutTimes();
       send += buildMediaPickOrDeliver();

//       alert(send);
   if (validForm == "true")
   {
       httpRequest = createXMLHttpRequest();

       if (httpRequest != null)
       {
           if (httpRequest.overrideMimeType)
           {
               httpRequest.overrideMimeType('text/xml');
           }
           httpRequest.open("GET", send, true);
           httpRequest.onreadystatechange = handleValidateMediaEquip;
           httpRequest.send(null);
       }
   }
   else if (validForm == "false")
   {
      alert(validationErrorMsg);
   }

}

///////////////////////////////////////////////////////////////////////

function handleChangeMediaItem()
{
   ///alert(httpRequest.readyState);
   //if(httpRequest.readyState == 0) { document.getElementById("messageArea").innerHTML = 'Creating Request Object...'; }
   //if(httpRequest.readyState == 1) { document.getElementById("messageArea").innerHTML = 'Loading Request Object...'; }
   //if(httpRequest.readyState == 2) { document.getElementById("messageArea").innerHTML = 'Request Object Loaded! Sending....'; }
   //if(httpRequest.readyState == 3) { document.getElementById("messageArea").innerHTML = 'Receiving Data....'; }
   if(httpRequest.readyState == 4) // Page Complete
   {
//      document.getElementById("messageArea").innerHTML = 'Receive Complete....';
      if (httpRequest.status == 200)
      {
         // Text returned FROM the servlet
         var response = httpRequest.responseXML;

         if(response)
         {
            // UPDATE content
            populateBasicDD('equipment','equipTypes');
            populateBasicDD('pickUpLocations','PICK');
         }
      }
      else
      {
         document.getElementById("messageArea").innerHTML = 'Error Recieving Data....'+ httpRequest.status +":"+ httpRequest.statusText;
      }
   }
}

////////////////////////////////////////////////////////////////////////
// reqNodeName - this is the name of the node in the responseText XML //
//               in which to grab the data from                       //
// ddId        - this is the id of the dropDown in html where to put  //
//               the new values found in the XML                      //
////////////////////////////////////////////////////////////////////////

function populateBasicDD(reqNodeName,ddId)
{
   var myDropDown = document.getElementById(ddId);    // use DOM to get to our dropdown
       myDropDown.options.length = 0;                 // clear out the old values

   var xml = httpRequest.responseXML;                 // grab the xml from the xml response

   var eleNode=getTagName(xml,reqNodeName);           // parse thru the responseXML to the requested node name

   // Loop thru the child elements of the parent node and build our dropDown data
   for (iEle=0;iEle<eleNode[0].childNodes.length;iEle++)
   {
      node = eleNode[0].childNodes[iEle];             // copy the node structure

      // assign the values
       isDefault = matchAttribute(node,'isDefault');
           idVal = matchAttribute(node,'id');
      displayVal = eleNode[0].childNodes[iEle].firstChild.nodeValue;

      // insert the values into the dropdown
      myDropDown.options[myDropDown.options.length] = new Option(displayVal,idVal);

      // default selection check
      if(isDefault=="Y")
      {
         myDropDown.options[myDropDown.options.length-1].selected = "selected";
      }
   }
}

///////////////////////////////////////////////////////////////////////

function handleValidateMediaEquip()
{
   ///alert(httpRequest.readyState);
   //if(httpRequest.readyState == 0) { document.getElementById("messageArea").innerHTML = 'Creating Request Object...'; }
   //if(httpRequest.readyState == 1) { document.getElementById("messageArea").innerHTML = 'Loading Request Object...'; }
   //if(httpRequest.readyState == 2) { document.getElementById("messageArea").innerHTML = 'Request Object Loaded! Sending....'; }
   //if(httpRequest.readyState == 3) { document.getElementById("messageArea").innerHTML = 'Receiving Data....'; }
   if(httpRequest.readyState == 4) // Page Complete
   {
//      document.getElementById("messageArea").innerHTML = 'Receive Complete....';
      if (httpRequest.status == 200)
      {
         // Text returned FROM the servlet
         var response = httpRequest.responseXML;

         if(response)
         {
            // UPDATE content
            if (isRequestBlocked(response))
            {
               validForm = "false";
            }
            else
            {
               // Booking Avail
               document.getElementById("messageArea").innerHTML = 'Booking is Available';
               x = document.getElementById("bookingButton");
               x.style.visibility = "";
               scheduleChecked = 'true';
            }
         }
      }
      else
      {
         document.getElementById("messageArea").innerHTML = 'Error Recieving Data....'+ httpRequest.status +":"+ httpRequest.statusText;
         scheduleChecked = 'false';
      }
   }
}

////////////////////////////////////////////////////////////////////////

function isRequestBlocked(response)
{

   var messageBlock = getTagName(response,"messages");

   messageNode = messageBlock[0].childNodes[0];

   var requestType = matchAttribute(messageNode,'type');

   if (requestType == "requestBlocked" || requestType == "blocked")
   {
      if (messageNode.textContent)
      {
         document.getElementById("messageArea").innerHTML = messageNode.textContent;
      }
      else
      {
         document.getElementById("messageArea").innerHTML = "Blocked";
      }
      return true;
   }
   if (requestType == "error")
   {
      document.getElementById("messageArea").innerHTML = messageNode.textContent;
      return true;
   }
   else { return false; }

}

////////////////////////////////////////////////////////////////////////

function buildEquipTypes()
{
   urlData = "";
   x=document.getElementById("equipTypes");

   for(i=0;i<x.options.length;++i)
   {
       if(x.options[i].selected)
       {
          if (urlData) { urlData += "&";}
          urlData += "equipTypes=" + x.options[i].value
       }
   }

   return urlData;
}

////////////////////////////////////////////////////////////////////////

function buildItems()
{
   urlData = "";
   x=document.getElementById("itemId");

   for(i=0;i<x.options.length;++i)
   {
       if(x.options[i].selected)
       {
          if (urlData) { urlData += "&";}
          urlData += "itemId=" + x.options[i].value
       }
   }

   if (!urlData) { validForm = "false"; validationErrorMsg += "["+ document.getElementById("itemId_label").textContent+"] is a required Field\n"; }

   return urlData;
}
////////////////////////////////////////////////////////////////////////

function buildCheckoutTimes()
{
    urlData = "";
   startTime=document.getElementById("startTime").value;
     endTime=document.getElementById("endTime").value;

   if (startTime) { urlData += "&startTime="+startTime; }
   if (!urlData)  { validForm = "false"; validationErrorMsg += "["+ document.getElementById("startTime_label").textContent+"] is a required Field\n"; }
   if (endTime)   { urlData += "&endTime="+endTime; }
   if (!urlData)  { validForm = "false"; validationErrorMsg += "["+ document.getElementById("endTime_label").textContent+"] is a required Field\n"; }
   return urlData;
}

////////////////////////////////////////////////////////////////////////

function buildMediaPickOrDeliver()
{

   x=document.forms[1].mediaPickOrDel;

   urlData = "";

   for(i=0;i<x.length;++i)
   {
      if(x[i].checked)
      {
         urlData += "&mediaPickOrDel="+x[i].value;
         urlData += buildPickOrDeliverDDData(x[i].value);
      }
   }
   if (!urlData)  { validForm = "false"; validationErrorMsg += "\nYou must choose a delivery method either ["+document.getElementById("PICK_label").textContent+"] or ["+document.getElementById("deliverLocId_label").textContent+"] as it is a required Field\n"; }
   return urlData;

}

////////////////////////////////////////////////////////////////////////

function buildPickOrDeliverDDData(radOpt)
{
   x = "";
   urlData = "";

   if (radOpt == '2')
   {
      urlData += "&deliverLocId=";
      x=document.getElementById("deliverLocId");
   }
   else if (radOpt == '3')
   {
      urlData += "&PICK=";
      x=document.getElementById("PICK");
   }
   else
   {
      return;
   }

   for(i=0;i<x.options.length;++i)
   {
       if(x.options[i].selected)
       {
          urlData += x.options[i].value
       }
   }
   return urlData;
}

////////////////////////////////////////////////////////////////////////

function hideEle(eleID)
{
   x = document.getElementById(eleID);
   x.style.visibility = "hidden";
}


////////////////////////////////////////////////////////////////////////
function updateMedia()
{
   if (scheduleChecked == 'true')
   {
      updMsgArea('messageArea','The booking form has changed. <br/> Please re-check the booking schedule.');
   }
}

////////////////////////////////////////////////////////////////////////

function updMsgArea(eleID,msgText)
{
   document.getElementById(eleID).innerHTML = msgText;
}

//////////////////////////////////////////////////////////////////////
function getTagName(xml,eleName)
{
   var xmlObj="";
   if(navigator.appVersion.indexOf("MSIE") != "-1")
   {
      xmlObj=xml.getElementsByTagName("req:"+eleName);
   }
   else
   {
      xmlObj=xml.getElementsByTagName(eleName);
   }
   return xmlObj;
}

//////////////////////////////////////////////////////////////////////

function showhide(layer_ref)
{

   if (state == 'block')
   {
      state = 'none';
   }
   else
   {
      state = 'block';
   }
   if (document.all) { //IS IE 4 or 5 (or 6 beta)
      eval( "document.all." + layer_ref + ".style.display = state");
   }
   if (document.layers) { //IS NETSCAPE 4 or below
   document.layers[layer_ref].display = state;
   }
   if (document.getElementById &&!document.all) {
   hza = document.getElementById(layer_ref);
   hza.style.display = state;
   }
}


//////////////////////////////////////////////////////////////////////

function changeMediaDeliveryLoc()
{
   validForm ="true";
   validationErrorMsg = "";

   var send = "changeMediaDeliveryLoc?";
       send += "deliverLocId=";
       send += document.getElementById("deliverLocId").value;

//       alert(send);
   if (validForm == "true")
   {
       httpRequest = createXMLHttpRequest();

       if (httpRequest != null)
       {
           if (httpRequest.overrideMimeType)
           {
               httpRequest.overrideMimeType('text/xml');
           }
           httpRequest.open("GET", send, true);
           httpRequest.onreadystatechange = handleChangeDeliveryLoc;
           httpRequest.send(null);
       }
   }
   else if (validForm == "false")
   {
      alert(validationErrorMsg);
   }

}

//////////////////////////////////////////////////////////////////////

function handleChangeDeliveryLoc()
{
   ///alert(httpRequest.readyState);
   //if(httpRequest.readyState == 0) { document.getElementById("messageArea").innerHTML = 'Creating Request Object...'; }
   //if(httpRequest.readyState == 1) { document.getElementById("messageArea").innerHTML = 'Loading Request Object...'; }
   //if(httpRequest.readyState == 2) { document.getElementById("messageArea").innerHTML = 'Request Object Loaded! Sending....'; }
   //if(httpRequest.readyState == 3) { document.getElementById("messageArea").innerHTML = 'Receiving Data....'; }
   if(httpRequest.readyState == 4) // Page Complete
   {
      //document.getElementById("messageArea").innerHTML = 'Receive Complete....';
      if (httpRequest.status == 200)
      {
         // Text returned FROM the servlet
         var response = httpRequest.responseXML;

         if(response)
         {
            // UPDATE content
            populateEquip();
         }
      }
      else
      {
         document.getElementById("messageArea").innerHTML = 'Error Recieving Data....'+ httpRequest.status +":"+ httpRequest.statusText;
      }
   }
}

//////////////////////////////////////////////////////////////////////

function populateEquip()
{
   var mySpan = document.getElementById('equipInRoom');    // use DOM to get to our dropdown
       mySpan.innerHTML = '';                 // clear out the old values

   var xml = httpRequest.responseXML;                 // grab the xml from the xml response

   var eleNode=getTagName(xml,"equipment");           // parse thru the responseXML to the requested node name
   var htmlChunk = '';

   // Loop thru the child elements of the parent node and build our dropDown data
   for (iEle=0;iEle<eleNode[0].childNodes.length;iEle++)
   {
      node = eleNode[0].childNodes[iEle];             // copy the node structure

      // assign the values
      displayVal = eleNode[0].childNodes[iEle].firstChild.nodeValue;

      // insert the values into the dropdown
      htmlChunk += displayVal + '<br/>';
   }

   mySpan.innerHTML = htmlChunk;
}

//////////////////////////////////////////////////////////////////////

function removeUpdateBtn()
{
   myObj = document.getElementById('top_link_page.searchResults.browseBar.update.button');
   removeUpdateBtnLogic(myObj);
   myObj = document.getElementById('bottom_link_page.searchResults.browseBar.update.button');
   removeUpdateBtnLogic(myObj);
   
}

//////////////////////////////////////////////////////////////////////

function removeUpdateBtnLogic(myObj)
{
   
   if(myObj)
   {
      myObj.innerHTML='';  // wipe out the button
 
      // We need to loop since mozilla finds whitespace and IE doesn't , so we need a node type of 1
      do myObj = myObj.previousSibling;
      while (myObj && myObj.nodeType != 1);
     
     // basically change the class from horizontal to endLine
      myObj.lastChild.previousSibling.className="endLine";
   }
}

//////////////////////////////////////////////////////////////////////

function sortBySubmit(obj)
{

// Drop down selected


// Point at the form
var resultsForm = document.getElementById('resultsForm');

// pretend we clicked the Update Button
updButton=document.createElement("input");
updButton.setAttribute("type","hidden");
updButton.setAttribute("name","update");
updButton.setAttribute("value","Update");

resultsForm.appendChild(updButton);

// Now submit the form
obj.form.submit();
}
//////////////////////////////////////////////////////////////////////

function makeRequest(url, parameters)
{
   httpRequest = createXMLHttpRequest();
   
   httpRequest.open("POST",  url + parameters, true);
   httpRequest.onreadystatechange = alertContents;
   httpRequest.send(null);
}

//////////////////////////////////////////////////////////////////////

//function alertContents()
//{
//   if (httpRequest.readyState == 4)
//   {
//      if (httpRequest.status == 200)
//      {
//         result = httpRequest.responseText;
//      }
//      else 
//      {
//         alert('Selection was not retained.');
//      }
//   }
//}   

//////////////////////////////////////////////////////////////////////

function selectTitleChkBx(obj)
{
   // this function simply unchecks the page checkbox when a title checkbox is checked

   if(document.getElementById('page'))       // make sure it exists
   {
      document.getElementById('page').checked=false;
   }

   // then via XHR update the current selections
   retainSelection(obj);
}

//////////////////////////////////////////////////////////////////////

function deselectAllCheckboxes(obj)
{

   // Loop thru them all
   for (i=0;i<obj.length;i++)
   {
      // and deselect them
      obj[i].checked=false;
   }
   
}

//////////////////////////////////////////////////////////////////////

function selectAllCheckboxes(obj,val)
{

   // Loop thru them all
   for (i=0;i<obj.length;i++)
   {
      // and deselect them
      obj[i].checked=val;
   }
   
}

//////////////////////////////////////////////////////////////////////

function selectAllCheckbox(obj,currSel)
{
   deselectAllCheckboxes(obj.page);
   selectAllCheckboxes(obj.all,currSel.checked);
   updateTitleCheckboxs(obj);
}

//////////////////////////////////////////////////////////////////////

function selectPageCheckbox(obj,currSel)
{
   //document.getElementById('all').checked=false;
   deselectAllCheckboxes(obj.all);
   selectAllCheckboxes(obj.page,currSel.checked);
   updateTitleCheckboxs(obj)
}

//////////////////////////////////////////////////////////////////////

function _getElementsByClassName (className,tag,elm)
{
   
   var tag = tag || "*";
	var elm = elm || document;
	var allElements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	
   //var allElements = document.all ? document.all : document.getElementsByTagName('*');
   var elementArray = new Array();
   for (var element = 0; element < allElements.length; element++)
   {
      if (allElements[element].className == className)
      {
         elementArray[elementArray.length] = allElements[element];
      }
   }
   return elementArray;
}

//////////////////////////////////////////////////////////////////////

function updateTitleCheckboxs(obj)
{

   // point at the titles array of checkboxes
   var titleChkBxs=obj.titles;
   
   // Loop thru them all
   for (i=0;i<titleChkBxs.length;i++)
   {
      // and select them
      titleChkBxs[i].checked=document.getElementById('page').checked;
   }
   
   // then via XmlHttpRequest update the current selections
   retainSelection(obj);
}

//////////////////////////////////////////////////////////////////////

function retainSelection(obj)
{
   var getstr = "?";
   
   for (i=0; i<obj.elements.length; i++)
   {
      if (obj.elements[i].tagName == "INPUT")
      {
         if (obj.elements[i].type == "text")
         {
            getstr += obj.elements[i].name + "=" + obj.elements[i].value + "&";
         }
         if (obj.elements[i].type == "hidden")
         {
            getstr += obj.elements[i].name + "=" + obj.elements[i].value + "&";
         }
      
         if (obj.elements[i].type == "checkbox")
         {
            if (obj.elements[i].checked)
            {
               getstr += obj.elements[i].name + "=" + obj.elements[i].value + "&";
            }
            else
            {
               getstr += obj.elements[i].name + "=&";
            }
         }
         if (obj.elements[i].type == "radio")
         {
            if (obj.elements[i].checked)
            {
               getstr += obj.elements[i].name + "=" + obj.elements[i].value + "&";
            }
         }
      }   
      if (obj.elements[i].tagName == "SELECT")
      {
         var sel = obj.elements[i];
         getstr += sel.name + "=" + sel.options[sel.selectedIndex].value + "&";
      }
   }
   makeRequest('savSelChkBx', getstr);


}

//////////////////////////////////////////////////////////////////////
