var mainframe;
var previousname = "";
function findMainFrame(frame) {
   if (!frame) return null;
   //When a single frame the frameset repeats
   if (previousname == frame.name) {
      return;
   }
   previousname = frame.name;
   if (frame.name == 'main') {
      mainframe = frame;
      return;
   }
   findMainFrame(frame.parent);
}

function removeSubsetBox(e) {
   findMainFrame(parent);
   try {
      var target;
      if (!e) e = window.event;
      if (e.target) target = e.target;
      else if (e.srcElement) target = e.srcElement;
      if (mainframe) {
         if (mainframe.content.tree.previousmenu) {
            isChildOf(target, mainframe.content.tree.previousmenu);
            if (!isChild) mainframe.content.tree.previousmenu.style.display = 'none';
         }
      }
   } catch (error) {
   }

   var icons = document.getElementById('charticons');
   if (icons) {
      if (target) {
         isChildOf(target, icons);
         if (!isChild) icons.style.display = 'none';
      }
   }


   removeBookmarkBox(e);

   if (domTT_selectElements) {
      for (var cnt = 0; cnt < domTT_selectElements.length; cnt++) {
         var thisSelect = domTT_selectElements[cnt];
         thisSelect.style.visibility = 'visible';
      }
   }
}

function removeBookmarkBox(e) {
   var target;
   if (!e) e = window.event;
   if (e.target) target = e.target;
   else if (e.srcElement) target = e.srcElement;

   var bookmarkmenu = document.getElementById('bookmarkmenu');
   if (bookmarkmenu) {
      isChildOf(target, bookmarkmenu);
      if (!isChild && bookmarkmenu.style.display == 'block') bookmarkmenu.style.display = 'none';
   }
}

function isChildOf(node, what) {
   isChild = false;

   while (node) {
      node = node.parentNode;
      if (!node) break;
      if (node && node.nodeType == 9) break;
      if (node.id == what.id) {
         isChild = true;
         break;
      }
   }

}


/**
 * Opens an empty window with a target which can be invoked by a href-call later on
 */
function openEmptyWindow(target) {
   awin = window.open('', target, 'toolbar=yes,location=yes,directories=no,status=yes,menubar=yes,resizable=yes,copyhistory=no,scrollbars=yes,width=800,height=600');
   if (awin) awin.focus();
   return true;
}


function setScrollableSize() {
  //For some reason this must be set
  if (browser.isIE && !browser.isIE7up) {
     var exploder = xGetElementById('exploder');
     if (exploder) {
        var newSizeY = xClientHeight() - (xPageY(exploder));
        var newSizeX = xClientWidth() - (xPageX(exploder));

        // adjust the size of the table to take into account the added size of a scrollbar
        var metadata = xGetElementById('metadata');
        if(metadata) {
           xHeight(metadata, newSizeX - 10);
        }

        var metadataview = xGetElementById('metadataview');
        if (metadataview) {
           newSizeY -= xHeight(metadataview);
        }

        // Sets the dimensions of the element to see if scrollbars are removed
        newSizeX = xClientWidth() - (xPageX(exploder));
        xWidth(exploder, newSizeX);
        newSizeY = xClientHeight() - (xPageY(exploder));
        xHeight(exploder, newSizeY);

        // Do the same operation again to place scrollbars correctly
        newSizeX = xClientWidth() - (xPageX(exploder));
        xWidth(exploder, newSizeX);
        newSizeY = xClientHeight() - (xPageY(exploder));
        xHeight(exploder, newSizeY);
     }
  }
}

function highlightSearch() {
   term = "";
   try{
      searchFrame = parent.parent.content.simpleSearch;

      indicatorField = false;
      searchField = false;

      if (searchFrame) {
         indicatorField = searchFrame.document.getElementById('lastClickInSearchIndicator');
         searchField = searchFrame.document.getElementById('currentSearchTerm');
      }

      if (!indicatorField || indicatorField.value != "true") return;

      if (searchField) {
         term = searchField.value;
      }

      var terms = term.split(' ');
      var finalterms=new Array()
      var inquotes="";
      var j=0;
      for (i = 0; i < terms.length; i++) {
         term=trim(terms[i]);
         if (term.indexOf("-") == 0 ) {
            term=term.substring(1,term.length);
            if (inquotes != "" ) i++;
            break;
         }

         if (term.indexOf("+") == 0) term=term.substring(1,term.length);

         if (term.indexOf("\"") == 0) {
            inquotes="\"";
            term=term.substring(1,term.length);

         }
         /* NOTE: This does not fit with java implementation. Only " counts as a quote
         if (term.indexOf("\'") == 0) {
            inquotes="\'";
            term=term.substring(1,term.length)
         }

         if (inquotes == "\'" && term.indexOf("\'") == term.length-1) {
            inquotes="end";
            term=term.substring(0,term.length-1);
         }
         */

         if (inquotes == "\"" && term.indexOf("\"") == term.length-1) {
            inquotes="end";
            term=term.substring(0,term.length-1);
            //console.info("Term ved quote end: "+term);
         }

         if (term == "NOT" && inquotes == "" ) {
            i++;
            break;
         }

         if (term == "AND") break;
         if (term == "OR") break;

         if (term != "") {
            if (inquotes == "") {
               finalterms[j++] = term;
            } else {
               if (undefined != finalterms[j]) {
                  finalterms[j] = finalterms[j] + " " + term;
               } else {
                  finalterms[j] = term;
               }
            }
         }
         if (finalterms[j]) trim(finalterms[j])
         if (inquotes == "end") {
            inquotes="";
            j++;
         }
      }
      highlightSearchTerms(finalterms);
   }catch(e){
      var a="Just to create a breakpoint for the debuger";
      //alert(e);
      //Do nothing
   }
}

// Removes leading whitespaces
function LTrim(value) {
   var re = /\s*((\S+\s*)*)/;
   return value.replace(re, "$1");

}

// Removes ending whitespaces
function RTrim(value) {
   var re = /((\s*\S+)*)\s*/;
   return value.replace(re, "$1");

}

// Removes leading and ending whitespaces
function trim(value) {

   return LTrim(RTrim(value));

}

function toCompensateY() {
   //If it is not IE, then no need to compensate
   if (!browser.isIE || browser.isIE7up) return 0;

   var topstrip = xGetElementById('topstrip');
   //Firs a negative compensated
   var compensated = 0 - xHeight(topstrip);
   //The IE scrollable area
   var exploder = xGetElementById('exploder');
   //Append the scroll to the compensated
   compensated += xScrollTop(exploder);
   return compensated;
}

function toCompensateX() {
   //If it is not IE, then no need to compensate
   if (!browser.isIE || browser.isIE7up) return 0;
   //The IE scrollable area
   var exploder = xGetElementById('exploder');
   if (!exploder) return 0;
   //Append the scroll to the compensated
   return xScrollLeft(exploder);
}


/***********************************************************
 **
 **
 ** E-mail verification
 **
 **
 **
 *************************************************************/

function getAndValidateEmail(formid, link) {
   var form = xGetElementById(formid);
   var isOk = validate(form);
   if (!isOk) return false;

   link.href = link.href + "&email=" + form.email.value;
   return true;
}

function validate(form) {
   return emailCheck(form.email.value);
}


function emailCheck(emailStr) {

   /* The following variable tells the rest of the function whether or not
to verify that the address ends in a two-letter country or well-known
TLD.  1 means check it, 0 means don't. */

   var checkTLD = 1;

   /* The following is the list of known TLDs that an e-mail address must end with. */

   var knownDomsPat = /^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

   /* The following pattern is used to check if the entered e-mail address
fits the user@domain format.  It also is used to separate the username
from the domain. */

   var emailPat = /^(.+)@(.+)$/;

   /* The following string represents the pattern for matching all special
characters.  We don't want to allow special characters in the address.
These characters include ( ) < > @ , ; : \ " . [ ] */

   var specialChars = "\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

   /* The following string represents the range of characters allowed in a
username or domainname.  It really states which chars aren't allowed.*/

   var validChars = "\[^\\s" + specialChars + "\]";

   /* The following pattern applies if the "user" is a quoted string (in
which case, there are no rules about which characters are allowed
and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
is a legal e-mail address. */

   var quotedUser = "(\"[^\"]*\")";

   /* The following pattern applies for domains that are IP addresses,
rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
e-mail address. NOTE: The square brackets are required. */

   var ipDomainPat = /^\[(\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 userPat = new RegExp("^" + word + "(\\." + word + ")*$");

   /* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */

   var domainPat = 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(emailPat);

   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_incorrect);
      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(email_user_incorrect);
         return false;
      }
   }
   for (i = 0; i < domain.length; i++) {
      if (domain.charCodeAt(i) > 127) {
         alert(email_domain_incorrect);
         return false;
      }
   }

   // See if "user" is valid

   if (user.match(userPat) == null) {

      // user is not valid

      alert(email_incorrect);
      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(ipDomainPat);
   if (IPArray != null) {

      // this is an IP address

      for (var i = 1; i <= 4; i++) {
         if (IPArray[i] > 255) {
            alert(email_incorrect);
            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(email_incorrect);
         return false;
      }
   }

   // Make sure there's a host name preceding the domain.

   if (len < 2) {
      alert(email_incorrect);
      return false;
   }

   // If we've gotten this far, everything's valid!
   return true;
}


function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  } else var expires = "";

  var ck = name+"="+value+expires+"; path=/";
  document.cookie = ck;
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i<ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}


function eraseCookie(name) {
  createCookie(name,"",-1);
}