
/////////////////////////////////////////////////////////////////////////
// The 'mothership' function.  This is called on every WV page!
/////////////////////////////////////////////////////////////////////////
function do_footer_funcs ()
{
   if (is_ubreq()) {
      setup_early_submit_prevention();
      setup_aaa_fix();
   }
   help_engine();
   prevent_double_clicks();
   attach_new_search();
}
/////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////
// When servers are slow to respond, users often double-triple-etc.
// click submit buttons and links.  This causes even more slowdown for
// the servers.  Let's try to help out the servers with double-click
// prevention.
/////////////////////////////////////////////////////////////////////////
var last_time = null;
function first_click() {
   var this_time = (new Date()).getTime();
   if (this_time < last_time + 5000)
   {
      return false;
   }
   else
   {
      last_time = this_time;
      return true;
   }
}

function prevent_double_clicks()
{
   var oldfnstr;

   for (i=0; i<document.links.length; i++) { 

      if (document.links[i].target) {
         continue;
      }

      oldfnstr = "";
      if (document.links[i].onclick) {
         oldfnstr = document.links[i].onclick.toString();
         var inx = oldfnstr.indexOf(")");
         oldfnstr = oldfnstr.substr(inx+1);
      }
      oldfnstr += 
         "\
             if (first_click()) return true;\
             else alert(\"Please wait while the catalog responds.\");\
             return false;\
         ";
      document.links[i].onclick = new Function("event", oldfnstr);
   
   }
   for (j=0; j<document.forms.length; j++) { 

      var els = document.forms[j].elements.length;
      for (k=0; k<els; k++) {

         var obj = document.forms[j].elements[k];

         if (obj.type == 'submit') {

            oldfnstr = "";
            if (obj.onclick) {
               oldfnstr = obj.onclick.toString();
               var inx = oldfnstr.indexOf(")");
               oldfnstr = oldfnstr.substr(inx+1);
            }
            oldfnstr += 
               "\
                   if (first_click()) \
                   {\
                      return true;\
                   }\
                   else\
                   {\
                      alert(\"Please wait while the catalog responds.\");\
                      return false;\
                   }\
               ";
            obj.onclick = new Function("event", oldfnstr);

         }

      }
   }
}
/////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////
// Determine if we are on the infamous UB Request page
/////////////////////////////////////////////////////////////////////////
function is_ubreq()
{
   if (document.forms != null &&
       document.forms[0].name == 'ubreq') return true;
   return false;
}
/////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////
// fix the UB pages: don't allow patrons access to the submit
// button after changing the 'select library' or 'select pickup library'
// values; we need to wait for EIS' code to refresh to a new page!!!
// otherwise, we may find ourselves in an inconsistent state!!!
var prevent_submit_button = false;
function setup_early_submit_prevention()
{
   var els = document.ubreq.elements.length;
   for (var i=0; i<els; i++) {
      var obj = document.ubreq.elements[i];
      if (obj.type == 'button') {
         if (obj.value == 'Submit Request') {
            if (obj.onclick != null) {
               var newfnstr = "do_early_submit_prevention();";
               obj.onclick = new Function("event", newfnstr);
            }
         }
      }
   }

   var obj = document.ubreq.Select_Pickup_Lib;
   var oldfn = obj.onchange.toString();
   var newfn = prepend_code("pulibrary_onchange();", oldfn);
   obj.onchange = new Function("event", newfn);

}

// set up the new Event function by
// prepending pre_code to the original code
function prepend_code(pre_code, current_fn)
{
   var newfnstr = "{ " + pre_code;
   var inx = current_fn.indexOf("{");
   var oldfnstr = current_fn.substr(inx+1);
   var pre = newfnstr+oldfnstr;
   return pre;
}

function pulibrary_onchange()
{
   // dis-allow multiple re-selections
   // make user wait until next page comes up
   var obj = document.ubreq.Select_Pickup_Lib;
   obj.disabled = true;
   obj.onchange = new Function("event", "");

   prevent_submit_button = true;
}

function do_early_submit_prevention()
{
   if (check_for_resdb_pickup()) {
      return true;
   }

   if (prevent_submit_button) {
      alert("Please wait while the page refeshes.");
      return true;
   }

   // call Endeavor's original function (the one we replaced earlier)
   checkValues();
}

function check_for_resdb_pickup()
{
   var Pickup = document.ubreq.Select_Pickup_Lib.options[document.ubreq.Select_Pickup_Lib.selectedIndex].value.toString();

   var inx = Pickup.indexOf("RESDB");
   if (inx >= 0) {
      alert('Please choose a Pick-up Library');
      return true;
   }
   return false;
}

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

/////////////////////////////////////////////////////////////////////////
// Fix the AAA Scenarios 
/////////////////////////////////////////////////////////////////////////
function setup_aaa_fix()
{
   // replace/inject our version of these event functions
   document.ubreq.Select_Library.onchange = new Function("event", "carli_owninglibrary_changed(this)");
   document.ubreq.Select_Pickup_Lib.onchange = new Function("event", "carli_pickuplibrary_changed(this)");

   // start things off...
   carli_GetCopiesFor(document.ubreq.Select_Library);
   handleAAAScenario();
   // save the first holding lib id so we can revert if need be
   saveHoldingLibId = document.ubreq.Select_Library.selectedIndex;
}

// event functions
var saveHoldingLibId = null;
function carli_owninglibrary_changed(formobj) {

   carli_GetCopiesFor(document.ubreq.Select_Library);

   if (handleAAAScenario()) {
      // if it _is_ an AAA scenario, revert back to previous
      // (hopefully valid) selection
      document.ubreq.Select_Library.selectedIndex = saveHoldingLibId;
      carli_GetCopiesFor(document.ubreq.Select_Library);
   } else {
      // save this in case we need to revert back to it later
      saveHoldingLibId = document.ubreq.Select_Library.selectedIndex;
   }

}

function carli_pickuplibrary_changed(formobj) {
   if (handleAAAScenario()) {
      setPickupLocation(sPickupLib);
      return;
   }
   GetNewLocs();
}

function isCallSlipAllowed()
{
   var homeLib = extract_lib(sHomeLibId);
   var allowed = new Array();
   var num_allowed = 0;
   allowed[num_allowed++] = "AUG";
   allowed[num_allowed++] = "BEN";
   allowed[num_allowed++] = "BRA";
   allowed[num_allowed++] = "CTU";
   allowed[num_allowed++] = "DPU";
   allowed[num_allowed++] = "GRN";
   allowed[num_allowed++] = "GSU";
   allowed[num_allowed++] = "HRT";
   allowed[num_allowed++] = "IIT";
   allowed[num_allowed++] = "ISL";
   allowed[num_allowed++] = "ISU";
   allowed[num_allowed++] = "IWU";
   allowed[num_allowed++] = "JOL";
   allowed[num_allowed++] = "JUD";
   allowed[num_allowed++] = "JWC";
   allowed[num_allowed++] = "LCC";
   allowed[num_allowed++] = "LLC";
   allowed[num_allowed++] = "MCK";
   allowed[num_allowed++] = "NBT";
   allowed[num_allowed++] = "NEI";
   allowed[num_allowed++] = "NLU";
   allowed[num_allowed++] = "NPU";
   allowed[num_allowed++] = "OAK";
   allowed[num_allowed++] = "ONU";
   allowed[num_allowed++] = "QCY";
   allowed[num_allowed++] = "RMC";
   allowed[num_allowed++] = "ROU";
   allowed[num_allowed++] = "SIC";
   allowed[num_allowed++] = "SIE";
   allowed[num_allowed++] = "SIM";
   allowed[num_allowed++] = "SVC";
   allowed[num_allowed++] = "SXU";
   allowed[num_allowed++] = "TRN";
   allowed[num_allowed++] = "TRT";
   allowed[num_allowed++] = "UIC";
   allowed[num_allowed++] = "UIU";
   allowed[num_allowed++] = "USF";
   allowed[num_allowed++] = "WIU";
   for (var i=0; i<num_allowed; i++) {
      if (allowed[i]==homeLib) return true;
   }
   return false;
}

function getBBIDfromSelectedCopy()
{
   var sc = document.ubreq.Select_Copy.options[document.ubreq.Select_Copy.selectedIndex].value;
   var inx = sc.indexOf(".");
   if (inx >= 0) {
      sc = sc.substr(inx+1);
   }
   return sc;
}

function setPickupLocation(sLoc)
{
   for (var i = 0; i<arrPickupLibIds.length; i++) {
       if (arrPickupLibIds[i] == sLoc) {
            document.ubreq.Select_Pickup_Lib.options[i].selected = true;
            document.ubreq.Select_Pickup_Lib.options[i].defaultSelected = true;
            break;
      }
   }
}

function handleAAAScenario()
{
   var Pickup = document.ubreq.Select_Pickup_Lib.options[document.ubreq.Select_Pickup_Lib.selectedIndex].value.toString();
   var Holding = document.ubreq.Select_Library.options[document.ubreq.Select_Library.selectedIndex].value.toString();
   var Home = sHomeLibId.toString();

//var a = "Home:\t" + Home + "\n"
//+ "Holding:\t" + Holding + "\n"
//+ "Pickup:\t" + Pickup;
//alert(a);

   if (Home==Holding && Home==Pickup) {
      if (isCallSlipAllowed()) {

         var goto_url = 'http://i-share.carli.illinois.edu/' + extract_lib(Holding) + '/cgi-bin/Pwebrecon.cgi?DB=local&BBID=' + getBBIDfromSelectedCopy();
         aaa_popup('callslip', goto_url);
         return true;

      } else {
         var alertmsg = "You have selected to pick-up this item at the same\n";
         alertmsg +=    "location as the owning library.\n\n";
         alertmsg +=    "This is not supported in this catalog.\n";
         alert(alertmsg);
         return true;
      }
   }

   return false;
}


function aaa_popup(aaa_type, goto_url)
{
   var href = '/ilcso/cgi-bin/ubpopup.cgi?aaa_type=' + aaa_type + '&goto_url=' + escape(goto_url);
   var target = '';
   var props = 'scrollbars,resizable,width=600,height=400';

   window.open(href, target, props );
}


// scroll to an <a name> tag within the page
function move_to_aname(aname)
{
   var locstr = window.location.toString();
   var inx = locstr.indexOf("#");
   if (inx >= 0) {
      locstr = locstr.substr(0,inx);
   }
   locstr += '#' + aname;
   window.location = locstr;
}

// modified version of EIS GetCopiesFor()
function carli_GetCopiesFor(Lib)
{
   sHoldingLib = Lib.options[Lib.selectedIndex].value;
   document.ubreq.Select_Copy.options.length = 0;
   for (iIndex = 0; iIndex < arrDBIds.length; iIndex++)
   {
     if (arrDBIds[iIndex] == sHoldingLib)
     {
       var i = document.ubreq.Select_Copy.options.length;
       document.ubreq.Select_Copy.options[i] = new Option(arrCopyInfo[iIndex], arrItemKey[iIndex]);
       if (sSelectedCopy == arrItemKey[i] || (i==0 && sSelectedCopy.length == 0))
       {
         document.ubreq.Select_Copy.options[i].selected = true;
         document.ubreq.Select_Copy.options[i].defaultSelected = true;
       }
     }
   }
   carli_InitPickupLibs();
}

// modified version of EIS InitPickupLibs()
function carli_InitPickupLibs()
{
   document.ubreq.Select_Pickup_Lib.options.length = 0;
   for (i = 0; i < arrPickupLibNames.length; i++)
   {
     document.ubreq.Select_Pickup_Lib.options[i] = new Option(arrPickupLibNames[i], arrPickupLibIds[i]);
     if (arrPickupLibIds[i] == sPickupLib)
     {
        document.ubreq.Select_Pickup_Lib.options[i].selected = true;
        document.ubreq.Select_Pickup_Lib.options[i].defaultSelected = true;
     }
   }

   carli_GetCircDesks();
}

// modified version of EIS GetCircDesks()
function carli_GetCircDesks()
{
   document.ubreq.Select_Pickup_Desk.options.length = 0;
   for (i = 0; i  < arrPickupDeskIds.length; i ++)
   {
      document.ubreq.Select_Pickup_Desk.options[i] = new Option(arrPickupDeskNames[i],arrPickupDeskIds[i]);
     if (i == 0)
     { document.ubreq.Select_Pickup_Desk.options[i].selected = true;
       document.ubreq.Select_Pickup_Desk.options[i].defaultSelected = true;
     }
   }
}

function extract_lib(libstr)
{
   var inx = libstr.indexOf("@");
   return libstr.substr(inx+1,3);
}

/////////////////////////////////////////////////////////////////////////
// Rewrite URLs so they enter our 'help engine' (which preserves 
// WV sessions).
/////////////////////////////////////////////////////////////////////////
var website = 'http://eisweb4-dr.ilcso.uiuc.edu';
var website_ssl = 'https://eisweb4-dr.ilcso.uiuc.edu';
var website_domain = 'eisweb4-dr.ilcso.uiuc.edu';
var proxyhelp = 'http://eisweb4-dr.ilcso.uiuc.edu/ilcso/cgi-bin/proxyhelp.cgi';
var helpsrc = doc_src(document.location.href) + '/help';
var activatereturn = helpsrc + '/../cgi-bin/Pwebrecon.cgi?DB=local&PAGE=First';
var activatehelp = '/help/';

function help_engine()
{
   var pid;
   var i;
   var fields;
   var gotPid = 0;

   pid = get_pid();

//document.title = "PID=" + pid;
//document.write("<h1>PID=" + pid + "</h1>");

   var returndoc = activatereturn + "&PID=" + pid;

   // extract the PID from the embedded links
   for (i=0; i<document.links.length; i++) { 
      var theObject = document.links[i];
      if (theObject.href.indexOf(activatehelp) != -1) {
         //alert(theObject.href);
         // only "helpfiy" if the "/help" links come from us (ilcso.illinois.edu)
         if (theObject.href.indexOf(website_domain) != -1) {
            var url = theObject.href;
            var anchortag = anchor_tag(theObject.href);
            url = ld_fix(url);
            theObject.href = proxyhelp + '?helpdoc=' + escape(url) + '&return=' + 
                          escape(returndoc) + '&helpsrc=' + 
                          escape(helpsrc) + '&activate=' +
                          escape(activatereturn) + anchortag;
         }
      }
   }
}

// eisweb4-dr.ilcso.uiuc.edu is local director
// change this URL to real domain instead for resolution purposes
function ld_fix(doc)
{
   var newdoc;
   var newdocinx = doc.indexOf("http://uiccat.lib.uic.edu");
   if (newdocinx  != -1) {
      newdoc = website + '/uic' + doc.substring(25);
      doc = newdoc;
   }
   newdocinx = doc.indexOf("https://uiccat.lib.uic.edu");
   if (newdocinx  != -1) {
      newdoc = website_ssl + '/uic' + doc.substring(26);
      doc = newdoc;
   }
   newdocinx = doc.indexOf(website);
   if (newdocinx  != -1) {
      newdoc = website + doc.substring(website.length);
      doc = newdoc;
   }
   newdocinx = doc.indexOf(website_ssl);
   if (newdocinx  != -1) {
      newdoc = website_ssl + doc.substring(website_ssl.length);
      doc = newdoc;
   }
   return doc;
}

function doc_src(doc)
{
   doc = ld_fix(doc);

   var inx = doc.indexOf("http://");
   var lenOfMatch = 7;
   if (inx == -1) {
      inx = doc.indexOf("https://");
      lenOfMatch = 8;
   }
   if (inx == -1) return '';
   var docsrc = doc.substring(0, lenOfMatch);

   inx = doc.indexOf('/', lenOfMatch);
   if (inx == -1) return doc;

   // we need to go one more level deeper if
   // this webvoyage is proxied
   // (i.e., does NOT have notation of http://machine:port/)
   var saveinx = inx;
   inx = doc.indexOf('/', inx+1);
   if (inx == -1) return doc;
   var coloninx = doc.indexOf(':', lenOfMatch);
   if (coloninx != -1 && coloninx < inx) inx = saveinx;

   docsrc = doc.substring(0, inx);
   return docsrc;
}

function anchor_tag (url)
{
   var inx = url.indexOf("#");
   if (inx != -1) {
      return url.substring(inx);
   }
   return '';
}

function get_pid()
{
   return get_parm('PID=');
}
function get_seq()
{
   return get_parm('SEQ=');
}
function get_parm(parm)
{
   var pid = "";

   pid = get_parm_str(parm, document.location.href);
   if (pid.length > 0) {
      return pid;
   }
   for (i=0; i<document.links.length; i++) { 
      var theObject = document.links[i];
      pid = get_parm_str(parm, theObject.href);
      if (pid.length > 0) {
         return pid;
      }
   }
   var as = document.getElementsByTagName('a');
   for(var i =0; i < as.length; i++) {
      pid = get_parm_str(parm, as[i].href);
      if (pid.length > 0) {
         return pid;
      }
    }
   return "";
}

function get_pid_str(strUrl) {
   return get_parm_str('PID=', strUrl);
}
function get_seq_str(strUrl) {
   return get_parm_str('SEQ=', strUrl);
}
function get_parm_str(parm, strUrl)
{
   var pid = "";
   var inx = -1;

   // first split off from first question mark
   inx = strUrl.indexOf('?');
   if (inx != -1) {
      strUrl = strUrl.substring(inx);
      // strip all extraneous question marks
      while (strUrl.length > 1 && strUrl.charAt(0) == '?') {
         strUrl = strUrl.substring(1);
      }
   }
   
   var fields = collect_fields(strUrl, "&");
   for (var i=0; i<fields.length; i++) {
      inx = fields[i].indexOf(parm);
      if (inx != -1) {
         pid = fields[i].substring(inx+parm.length);
         break;
      }
   }
   return pid;
}

function set_parm_str(parm, val, strUrl)
{
   var pid = "";
   var inx = -1;
   var newUrl = "";

   // first split off from first question mark
   inx = strUrl.indexOf('?');
   if (inx != -1) {
      newUrl = strUrl.substring(0, inx+1);
      strUrl = strUrl.substring(inx);

      // strip all extraneous question marks
      while (newUrl.length > 1 && newUrl.charAt(newUrl.length-1) == '?') {
         newUrl = newUrl.substring(0, newUrl.length-1);
      }
      while (strUrl.length > 1 && strUrl.charAt(0) == '?') {
         strUrl = strUrl.substring(1);
      }
   }
   newUrl += '?';
   
   var fields = collect_fields(strUrl, "&");
   for (var i=0; i<fields.length; i++) {
      inx = fields[i].indexOf(parm);
      if (inx != -1) {
         newUrl += val;
      } else {
         newUrl += fields[i];
      }
      if (i < fields.length-1) newUrl += '&';
   }
   return newUrl;
}
/////////////////////////////////////////////////////////////////////////


/////////////////////////////////////////////////////////////////////////
// Rewrite our own 'new search' functionality in WV (to preserve sessions)
/////////////////////////////////////////////////////////////////////////
var new_search_url = '';
function attach_new_search() {
   var imgs = document.getElementsByTagName('img');
   for(var i = 0; i < imgs.length; i++) {
      if (imgs[i].src.indexOf('Search.gif') != -1) {
         new_search_url = imgs[i].parentNode.href;
         imgs[i].parentNode.href = 'javascript:new_search(new_search_url)';
      }
   }
}

function new_search(thisURL) {
   var newlink = set_parm_str('PAGE=sbSearch', 'PAGE=First', thisURL);
   window.location = newlink;
}
/////////////////////////////////////////////////////////////////////////


