var linkCounter = 0;
var isIE;
var isMac;

// used for debugging validateForm
var SHOW_ERRORS = false;


if(window.navigator.userAgent.indexOf("MSIE") != -1 && window.navigator.userAgent.indexOf("Opera") == -1 )
   isIE = true;
else if(window.navigator.userAgent.indexOf("Firefox") != -1)
   isIE = false;
else
   isIE = true;

if( window.navigator.platform.indexOf("Mac") != -1)
   isMac = true;
else
   isMac = false;

function initializer()
{
 if(getLogo())
      linkFootnotes("main_content");
}

function getLogo()
{
   if(screen.width <= 800)
      document.images.lib_logo.src = "http://www.library.arizona.edu/layout_imgs/logo_sm.gif";

   var myVersion = window.navigator.appVersion;
   myVersion = myVersion.substring(0,myVersion.indexOf(" "))
   myVersion = myVersion*1;
   var myBrowser = window.navigator.appName;
  
   if(myVersion < 4.9 && myBrowser.indexOf("Netscape")!= -1)
   {
      return false;
   }
   else
   {
      if(window.location.host.indexOf("sabio") != -1)
         fieldFocus();
      return true;
   }
}

// Used in the catalog as body onload="fieldFocus()"
function fieldFocus()
{
   var formDiv = document.getElementById("formArea");
      var inputArray = formDiv.getElementsByTagName("input");
      for(a = 0; a < inputArray.length; a++)
      {
         if(inputArray[a].type == "text")
         {
            inputArray[a].focus();
            break;
         }
   }
}

function linkFootnotes(myDiv)
{
   var localDomain = ".library.arizona.edu";

   var mainContent = document.getElementById(myDiv);
   var linkArray = mainContent.getElementsByTagName("a");
   
   // FOR ALL <A> TAGS...
   if(linkArray.length < 50)
   {
      for(var a = 0; a < linkArray.length; a++)
      {
         var thisURL = "";

         if(linkArray[a].getAttribute("href") != null && linkArray[a].parentNode.className != "page_menu" && linkArray[a].parentNode.className != "alpha_menu" && linkArray[a].className != "noFootnote" && linkArray[a].className != "noprint")
       thisURL = linkArray[a].getAttribute("href");

         var isMailTo = thisURL.indexOf("mailto:");
         var isLocal = thisURL.indexOf(localDomain);
         var isLinked = linkArray[a].innerHTML.indexOf("http://");
         var isFTP = linkArray[a].innerHTML.indexOf("ftp://");
         var isAnchor = thisURL.indexOf("#");
         var isJavaScript = linkArray[a].href.indexOf("javascript:");

         if(isMailTo != -1)
         {
       if(isLocal != -1)
       {
          linkArray[a].onmouseover = function test(){emailForm(this);}
          linkArray[a].onfocus = function test(){emailForm(this);}
          linkArray[a].onblur = function test(){emailLink(this);}
          linkArray[a].onmouseout = function test(){emailLink(this);}
       }
       if(linkArray[a].innerHTML.indexOf("@") == -1)
          printLink(linkArray[a]);
         }
         else if(isLinked == -1 && isFTP == -1 && isJavaScript == -1 && thisURL != "")
         {
             if(isAnchor != -1 && isLocal != -1)
               return;
             else
         printLink(linkArray[a]);
         }
   }
   }
}

function emailForm(thisLink)
{
   if(thisLink.href.indexOf("mailto:") != -1)
   {
      var mailToValue = thisLink.href;
      var displayText = thisLink.innerHTML;
      mailToValue = mailToValue.substr((mailToValue.indexOf("mailto:")+7),(mailToValue.indexOf("@")-7));
      if(thisLink.href.indexOf("@ccp.library.arizona.edu") != -1)
         mailToValue = mailToValue + "c";
      else
         mailToValue = mailToValue + "u";

      thisLink.href = "http://www.library.arizona.edu/cgi-bin/staffmail.pl?"+mailToValue;
      thisLink.innerHTML = displayText;
   }
}

function emailLink(thisLink)
{
   if(thisLink.href.indexOf("javascript") != -1)
   {
      var mailToValue = thisLink.href;
      var startIndex = mailToValue.indexOf("alert('") + 7;
      var endIndex = mailToValue.indexOf("');");
      mailToValue = mailToValue.substr(startIndex,(endIndex-startIndex));
      thisLink.href = "mailto:"+mailToValue+"@u.library.arizona.edu";
    }
}


/**********************************
* Removes given tag (or all tags)
* from given string.
**********************************/
function stripTags(str,tag)
{
   if(tag == "ALL")
      tag = "[\\w]";
   else tag = "[" + tag + "]";

   var tagRegExp = RegExp("<"+ tag +"[^>]+>", "gi");
   str = str.replace(tagRegExp,"");
   return str;
}

function printLink(thisLink)
{
   linkCounter++;
   var thisURL = thisLink.href.replace("mailto:","");
   var displayText = thisLink.innerHTML;
   var setBR = "";
   
   /****************************************
   * Contribute sometimes adds a line break
   * at the end of a link (STUPID!) so we'll
   * be sure to put our footnote before it if
   * it's there!
   *****************************************/
   
   var brString = RegExp("(<+" + "br" + "+>)");
   if(displayText.match(brString))
   {
      setBR = "<br />";
      displayText = stripTags(displayText,"br");
   }

   displayText = displayText + "<span class=\"printOnly\"><sup>[" + linkCounter + "]</sup></span>" + setBR;
   thisLink.innerHTML = displayText;
   
   var printFootnotes = document.getElementById("urlFooter");
   var footnotesHTML = printFootnotes.innerHTML;
   
   footnotesHTML = footnotesHTML + "<br />\n[" + linkCounter + "] " + thisURL;
   printFootnotes.innerHTML = footnotesHTML;
}

/****************************************************
 * METHOD NAME: validateForm                        *
 *                                                  *
 * DESCRIPTION: Validate all elements in a given    *
 *              form which have a class value       *
 *              containing the word required.       *
 *                                                  *
 *              For select boxes, it will require   *
 *              the user to select something other  *
 *              than the first (default) option.    *
 *                                                  *
 *              Change: If there is a parent node   *
 *              surrounding the select, then it     *
 *              will be highlighted  --Gene         *
 *                                                  *
 *              For radio buttons, it will require  *
 *              that one of the options has been    *
 *              selected. If there is a parent node *
 *              surrounding the set of radio        *
 *              buttons (that is not the form       *
 *              itself), then it will be            *
 *              highlighted.                        *
 *                                                  *
 *              For text boxes, it will do an       *
 *              additional check to see if the      *
 *              element name contains the word      *
 *              "email". If it does, it will try to *
 *              validate the email address using    *
 *              another function called             *
 *              validateEmail().                    *
 *                                                  *
 *              This does not cover "file-select"   *
 *              fields.                             *
 *                                                  *
 * PARAMETERS:  theForm - the form being validated. *
 *                                                  *
 * RETURNS:     Boolean - If the form is valid, it  *
 *              returns true. Otherwise, it alerts  *
 *              the user to the error and returns   *
 *              false.                              *
 ****************************************************/
function validateForm(theForm)
{
   // Give the user the benefit of the doubt.
   var isValid = true;

   // Initialize our default error message.
   var errorMessage = "Please fill out all required fields.\nMissing or unselected items are marked in red.\nThank you.";

   // Loop through every element in the form
   for(a = 0; a < theForm.elements.length; a++)
   {
      // Get the element.
      var thisField = theForm.elements[a];
      
      // Get the class name.
      var thisClass = thisField.className;

     /***************************************
      * If the current element is required, *
      * then we check to see if it's valid. *
      * Otherwise, we ignore it.            *
      ***************************************/
      if(thisClass.indexOf("required") != -1)
      {
        /************************************
         * If the element is a select box,  *
         * then we make sure that the user  *
         * has selected something other     *
         * than the first element in the    *
         * drop-down menu. If they haven't, *
         * then we highlight the parent     *
         * node and set isValid to false.   *
         ************************************/
         if(thisField.type == "select-one")
         {
            if(thisField.selectedIndex == 0)
            {
               thisField.parentNode.style.border = "1px solid red";
               if(document.getElementById(thisField.id+"Label"))
                  document.getElementById(thisField.id+"Label").style.color = "red";
               isValid = false;
            }
         }
        /***********************************
         * If the element is a text input, *
         * then we make sure that it's not *
         * blank. If it is, then we        *
         * highlight the parent node and   *
         * set isValid to false.           *
         ***********************************/
         else if(thisField.type == "text" || thisField.type == "password" || thisField.type == "file")
         {
            // Trim off any leading or trailing white space.
            if(trimAll(thisField.value) == "")
            {
               thisField.style.border = "1px solid red";
               if(document.getElementById(thisField.id+"Label"))
                  document.getElementById(thisField.id+"Label").style.color = "red";
               isValid = false;
            }
           /***********************************
            * If the text input isn't blank,  *
            * then we check to see if it's an *
            * email field. If it is, then we  *
            * try to validate the input as a  *
            * valid email address.            *
            ***********************************/
            else 
            {
               var fieldName = thisField.name;
               var mailpat =/email/i;
               if (fieldName.match(mailpat) != null )
               {
                  var emailStr = thisField.value;
                  // Check the email and alert the user to any errors.
                  if(!validateEmail(emailStr, SHOW_ERRORS))
                  {
                     if(document.getElementById(thisField.id+"Label"))
                        document.getElementById(thisField.id+"Label").style.color = "red";
                     isValid = false;
                     errorMessage = "Please enter a valid email address.";
                  }
               }
            }
         }
        /***********************************
         * If the element is a textarea,   *
         * then we make sure that it's not *
         * blank. If it is, then we        *
         * highlight the parent node and   *
         * set isValid to false.           *
         ***********************************/
         else if(thisField.type == "textarea")
         {
            if(thisField.value == "")
            {
               thisField.style.border = "1px solid red";
               if(document.getElementById(thisField.id+"Label"))
                  document.getElementById(thisField.id+"Label").style.color = "red";
               isValid = false;
            }
         }
        /*************************************
         * If the element is a radio button, *
         * then we make sure that something  *
         * has been chosen from the options. *
         * If nothing has been selected, we  *
         * highlight the parent node and set *
         * isValid to false.                 *
         *************************************/
         else if(thisField.type == "radio")
         {
            // Get the whole set of radio button options.
            var radiogroup = theForm.elements[thisField.name];
            var isChecked = false;

            for (i=0; i<radiogroup.length; i++)
            {
               if (radiogroup[i].checked)
               {
                  isChecked = true;
                  break;
               }
            }
            
            if(!isChecked)
            {
               isValid = false;
               if(thisField.parentNode.tagName != "FORM")
               {
                  thisField.parentNode.style.border = "1px solid red";
                  if(document.getElementById(thisField.name+"Label"))
                     document.getElementById(thisField.name+"Label").style.color = "red";

               }
            }
         }
      }
   }
   
   // If the form isn't valid, alert the user.
   if(!isValid)
      alert(errorMessage);

   return isValid;
}


/*********************************************
* This is a rewrite of the common trim
* function native to many programming
* languages, but not to Javascript!
**********************************************/
function trimAll(sString)
{
   // Need to make sure we have a string.
   sString = sString.toString();

   // Trim from the front
   while (sString.substring(0,1) == ' ')
   {
      sString = sString.substring(1, sString.length);
   }

   // Trim from the back
   while (sString.substring(sString.length-1, sString.length) == ' ')
   {
      sString = sString.substring(0,sString.length-1);
   }

   return sString;
}


/*********************************************
* This is a massive email validation script!
* It uses lots of regular expressions
* and covers a lot of bases.
* Read comments for further detail.
*********************************************/
function validateEmail(emailStr)
{
   var checkTLD=1;
   
   var knownDomainsPattern=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

   // Specify user@domain format
   var emailPattern=/^(.+)@(.+)$/;

   // Things we don't want ...
   var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

   // (allow everything but the above)
   var validChars="\[^\\s" + specialChars + "\]";

   // allow for quoted user names
   var quotedUser="(\"[^\"]*\")";

   // allow for domains in IP format
   var ipDomainPattern=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;


   /* The following string represents an atom (basically a series of non-special characters.) */

   var atom=validChars + '+';

   /* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */

   var word="(" + atom + "|" + quotedUser + ")";

   // The following pattern describes the structure of the user

   var userNamePattern = new RegExp("^" + word + "(\\." + word + ")*$");

   /* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPattern, shown above. */

   var domainNamePattern = new RegExp("^" + atom + "(\\." + atom +")*$");

   /* Finally, let's start trying to figure out if the supplied address is valid. */

   /* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */

   var matchArray=emailStr.match(emailPattern);

   if (matchArray==null)
   {
      /* Too many/few @'s or something; basically, this address doesn't
      even fit the general mould of a valid e-mail address. */

      alert("Email address seems incorrect (check @ and .'s)");
      return false;
   }

   var user=matchArray[1];
   var domain=matchArray[2];

   // Start by checking that only basic ASCII characters are in the strings (0-127).

   for (i=0; i<user.length; i++)
   {
      if (user.charCodeAt(i)>127)
      {
         alert("Ths username contains invalid characters.");
         return false;
      }
   }

   for (i=0; i<domain.length; i++)
   {
      if (domain.charCodeAt(i)>127)
      {
         alert("Ths domain name contains invalid characters.");
         return false;
      }
   }

   // See if "user" is valid 

   if (user.match(userNamePattern)==null) 
   {
      // user is not valid
      alert("The username doesn't seem to be valid.");
      return false;
   }


   /* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */

   var IPArray=domain.match(ipDomainPattern);
   if (IPArray!=null) 
   {

      // this is an IP address

      for (var i=1; i<=4; i++) 
      {
         if (IPArray[i]>255)
         {
            alert("Destination IP address is invalid!");
            return false;
         }
      }
      return true;
   }

   // Domain is symbolic name.  Check if it's valid.

   var atomPat=new RegExp("^" + atom + "$");
   var domArr=domain.split(".");
   var len=domArr.length;

   for (i=0;i<len;i++) 
   {
      if (domArr[i].search(atomPat)==-1) 
      {
         alert("The domain name does not seem to be valid.");
         return false;
      }
   }

   /* domain name seems valid, but now make sure that it ends in a
   known top-level domain (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding 
   the domain or country. */

   if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomainsPattern)==-1) 
   {
      alert("The address must end in a well-known domain or two letter country.");
      return false;
   }

   // Make sure there's a host name preceding the domain.
   if (len<2) 
   {
      alert("This address is missing a hostname!");
      return false;
   }

   // If we've gotten this far, everything's valid!
   return true;

}

/*******************************************
* Function to open a browser help window
* It may not be perfect for every occasion, 
* but it gives a reasonable window size, etc.
*******************************************/

function displayHelp(answer)
{
    window.open(answer,'popup_window','scrollbars=1,width=550,height=300')
}

/*******************************************
* Temporary function to allow the toggling
* of style sheets on and off.
*******************************************/

function toggleSheets2()
{
   var i=0;
   if(document.styleSheets.length>0)
   {
      cs=!document.styleSheets[0].disabled;

      for(i=0;i<document.styleSheets.length;i++)
         document.styleSheets[i].disabled=cs;
   }
}
