function substituteHref(s) {
// take a URL, get the url only, then change the location to it.
   document.location=getUrlFromHref(s);
};

function trimWS (str) { 
   if (str) {
      var s = str.replace(/\&nbsp\;/g, ' ');
      for (var i=s.length-1; i>0 && ((s.charCodeAt(i)==32) || (s.charCodeAt(i)==47) || (s.charCodeAt(i)==58) || (s.charCodeAt(i)==44)); i--);
      return s.slice(0,i+1);
   }
};

// Removes begin and end WS
function trimBEWS(str) {
   str = str.replace(/\&nbsp\;/g, ' ');
   return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}; // trimBEWS

// Gets rid of common punctuation and white space from the end
function stripTrailPunc(inStr) {
   if (inStr) {
      var s = inStr.replace(/\&nbsp\;/g, ' ');
      for (var i=s.length-1; i>0 && ((s.charCodeAt(i)>=32 && s.charCodeAt(i)<=47) || (s.charCodeAt(i)==58)); i--);
      return s.slice(0,i+1);
   }
};

// Change the tab_filing punctuation to encoded chars in scan
function encodeFiling(str) {
   if (str && (str != '')) {
      str = str.replace(/"/,'%22').replace(/!/,'%23').replace(/#/,'%21');
      return str;
   } else {
      return '';
   }
}; // stripQuotes

// Remove encoded tab_filing punctuation
function unencodeFiling(str) {
   str = str.replace(/%22|%23|%21|\"|#|!/,'').replace(/%20/,' ');
   return str;
};

// Checks for a numeric or white space string and returns true if numeric/false if not
function isNumeric(inStr) {
   if (inStr) {
      return inStr.length ? !isNaN(inStr.replace(/\s/,"z")/1) : true;
   } else {
      return false;
   }
   
};
   
// sets the location
function changeWindowLoc(inURL) {
   if (inURL != '') {
      window.location.href = inURL;
   }
};

// Given inStr, pad with padVal in front, to a total length of totalLen
function padLeft(inStr, totalLen, padVal) {
   for (var i = inStr.length; i < totalLen; i++) {
      inStr = padVal + inStr;
   }
   return inStr;
};

// gets back the session from a passed in string or windows.location   
function getSession(inURL) {
   if (inURL == '') { inURL = unescape(window.location.href); }
   var currSession = inURL.substring(inURL.indexOf('/F/') + 3);
   var endIndex = currSession.indexOf('?');
   if (endIndex < 0) endIndex = currSession.length;
   currSession = currSession.substring(0, endIndex);
   return currSession;
} // getSession
   
// Given a url in form <a href=url>text</a> return just the url
function getUrlFromHref(inHref) {
   var regEx = /HREF\s*=(\")?/i;
   var ar = regEx.exec(inHref);
   var urlOnly;
   if (ar == null) {
      urlOnly = inHref;
   }
   else {
      // need to account for anything after the href
      urlOnly = inHref.substring(ar.index + ar[0].length)
      var endref = urlOnly.search(/\'|\"|>/);
      if (endref > 0) {
         urlOnly = urlOnly.substring(0,endref);
      }
   }
   return urlOnly;
};

function getDescFromHref(inHref) {
// Given a url in form <a href=url>text</a> return just the text
   // get firstIndex of >
   var startIndex = inHref.indexOf('>');
   var endIndex = inHref.indexOf(/<\/a>/i);
   if ((startIndex < 0) && (endIndex < 0)) {
      // just text, not a link
      return inHref;
   } else {
      return inHref.slice(startIndex + 1, endIndex - 3);
   }      
}

function getFullQS(inURL) {
// Given a URL, returns everything after the ?.  First strip out the html href if there
   var urlOnly = unescape(getUrlFromHref(inURL));
   var regEx = /\?/;
   var ar=regEx.exec(urlOnly)
   if (ar == null) {
      urlOnly = '';
   }
   else {
      urlOnly = urlOnly.slice(ar.index + ar[0].length, urlOnly.length);
   }
   return urlOnly;
}; 

// If a button is not dimmed, get the navigation link
function getNavLink(inLink) {
   var convLink = '';
   if (!inLink.match(/\-dim\.gif/)) {
      var convLink = getUrlFromHref(inLink);
      convLink = convLink.replace(/\"/, '');
   }
   return convLink;
}; // getNavLink

function getLinkText(inURL) {
// Given an href url, get the link text back.
   var beginIndex = inURL.indexOf('>');
   var textVal = inURL.slice(beginIndex + 1, inURL.length);
   textVal = textVal.slice(0, textVal.indexOf('<'));
   return textVal;
}; // getLinkText

// Have to scrape the page for td containing inKeyValue, only need first one
function getKeyNumber(inKeyValue) {
   var linksList = document.getElementsByTagName('td');
   var i = 0, foundSet = false, key_num = "";
   var regexS = new RegExp("[\\^?\=\&]" + inKeyValue + "\=([^&$]*)", "gi");
   while (i < linksList.length && !foundSet) {
      var matches = linksList[i].innerHTML.match(regexS)
      if (matches) {
         key_num = matches[0].substring(matches[0].indexOf('=') + 1)
         foundSet = true;
      }
      i++;
   }
   return key_num;
};

// Given a URL, get the full query string
function getFullQS(inUrl) {
   var regEx = /\?/;
   var ar=regEx.exec(inUrl)
   if (ar == null) {
      inUrl = '';
   }
   else {
      inUrl = inUrl.substring(ar.index);
   }
   return inUrl;
}; // getFullQS

function queryString(s, inUrl)
// returns search string value from URL.  Pass in field and returns value
// for example: http://xyz.com/test.htm?a=alpha&b=beta
//   QueryString('a') returns 'alpha'
//   QueryString('b','http://xyz.com/test.htm?a=alpha&b=beta') returns 'beta'
{
  if (!inUrl) {
     inUrl = window.location.search;
  } else {
     inUrl = getFullQS(inUrl);
  }
  var searchString = "&" + unescape(inUrl).slice(1) + "&";
  var searchValueStart =  searchString.indexOf("&" + s + "=");

  if (searchValueStart == -1) return '';

  searchValueStart += s.length + 2;  // add length of '&name='
  return searchString.slice(searchValueStart, searchString.indexOf("&", searchValueStart));
};

hideNavigation = false;
// Given a form type, set the tab image
function changeTabImg(inServer, inForm)
{
   var isMyAccount = false;
   switch (inForm) {
      case 'search': 
         setActiveNav('asearch');
         break;
      case 'results': 
         setActiveNav('aresults');
         break;
      case 'history': 
         setActiveNav('ahistory');
         break;
      case 'myaccount':
         setActiveNav('amyaccount');
         hideMainTabs(inServer, true);
         isMyAccount = true;
         break;
      case 'maallon':
         setActiveNav('amyaccount');
         hideMainTabs(inServer, true);
         isMyAccount = true;
         break;
      case 'maholds':
         setActiveNav('aholds');
         hideMainTabs(inServer, true);
         isMyAccount = true;
         break;
      case 'mabooking':
         setActiveNav('aholds');
         hideMainTabs(inServer, true);
         isMyAccount = true;
         break;
      case 'maill':
         setActiveNav('aill');
         hideMainTabs(inServer, true);
         isMyAccount = true;
         break;
      case 'maloans':
         setActiveNav('aloans');
         hideMainTabs(inServer, true);
         isMyAccount = true;
         break;
      case 'mapin':
         setActiveNav('apin');
         hideMainTabs(inServer, true);
         isMyAccount = true;
         break;
      case 'marequests':
         setActiveNav('aholds');
         hideMainTabs(inServer, true);
         isMyAccount = true;
         break;
      case 'none':
         hideMainTabs(inServer, false);
         break;
   }
}; // changeTabImg

// For specific pages, turn off the main nav tabs, and if MyAccount, set specific map & other nav tabs
// Also - set the timeouts for any that are myaccount/hold/ill/login
function hideMainTabs(inServer, setMyAcctTabs) {
   window.setTimeout('window.close(); ',300000);
   hideElement('trmainnav');
   getElement('mainnavbanner').useMap = '#acctnavmap';
//   getElement('mainnavbanner').src = inServer + '/images/opac/account_nav_banner.gif';
   getElement('mainnavbanner').src = inServer + '/search/maintenance.asp?banner=myaccount';
   if (setMyAcctTabs) {
      getElement('yourlibbanner').useMap = '#accounttabs';
   showElement('trmyaccountnav');
   } else {
      hideElement('bannerstripe');
      
      getElement('yourlibbanner').useMap = '';
   }
   hideNavigation = true;
}; // hideMainTabs

// For a given field, set the element active
function setActiveNav(inelementid) {
   getElement(inelementid).style.backgroundColor='#B5CBE7';
   getElement(inelementid).style.color='maroon';
}; // setActiveNav

// Given a base, change the banner
function changeBanner(inServer, inLibCode) 
{
//   var newImage = "url('" + inServer + "/banner.asp?lib_code=" + inLibCode + "')";
   var newImage = inServer + "/banner.asp?lib_code=" + inLibCode;
   getElement('yourlibbanner').src = newImage;
};

/*
  Given a local base, get back the lib_code
  in: inLocalBase
  out: 'flcc0100' or the lib_code
  
  note: the keys in the collegelist are upper case, so it has to be converted if 
     making the calls
*/
function getLibCodeFromBase(inLocalBase) {
   var convBase = inLocalBase, outLibCode = '';
   // This is for the banner or LINCCWeb links, so check the cookie first
   if (get_cookie('bor_library')) {
      convBase = get_cookie('bor_library');
   }
   if (convBase.match(/all|fcc/i)) {
      return 'flcc0100';
   }
   if (convBase  != '') {
      if (convBase.length > 3) {
         convBase = convBase.substring(0,3);
      }
   } else {
      convBase = getLocalBase();
   }
   if (convBase != '') {
      convBase = convBase.toUpperCase();
      if (collegelist[convBase]) {
         outLibCode = collegelist[convBase].getLibCode();
      }
   }
   return outLibCode;
}; // getLibCodeFromBase

// Pass in the &base, check first the cookie
function getPrefBase(inBase) {
   var checkBase = getLocalBase();
   if ((!checkBase) || ((checkBase == '') || (checkBase.match(/all|fcc/i)))) {
      checkBase = inBase;
   }
   return checkBase;
}; // getPrefBase

function getLocalBase()
// assumes the local_base is in either the form1 or the querystring
{
   var lbase = '';
   if (get_cookie('bor_library')) {
      lbase = get_cookie('bor_library');
   }
   if ((lbase == '') && (document.getElementById('local_base')))
   {
      lbase = document.getElementById('local_base').value;
   }
   if (lbase == '')
   {
      lbase = queryString('local_base', '')
   }
   if ((lbase == '') && (document.getElementById('ILLUNIT')))
   {
      lbase = document.getElementById('ILLUNIT').value;
   }
   if ((lbase == '') && (document.getElementById('sub_library')))
   {
      lbase = document.getElementById('sub_library').value;
   }
   if (lbase == '')  {
      lbase = queryString('doc_library');
   }
   if (lbase == '') {
      lbase = queryString('adm_library');
   }
   if (lbase.length > 3) {
      lbase = lbase.slice(0,3);
   }
   return lbase;
};

// Given a base, find out if the reserves should be turned on  
function hasReserves(inBase) {
   var baseHasReserves = false;
   if (inBase == '') inBase = getLocalBase();
   if ((inBase == '') || (inBase.match(/all/i))) {
      baseHasReserves = false;  
   } else {
      if (inBase.length > 3) {
         inBase = inBase.substring(0,3);
      }
      var currColl = collegelist[inBase.toUpperCase()];
      if (currColl) {
         baseHasReserves = currColl.getReserves();
      } else {
         baseHasReserves = false;
      }
   }
   return baseHasReserves;
};


//
function cclaWindow(l,n) { // open a window at location (l) with name (n)
  var w=window.open('',n,'width=800,height=800,menubar=yes,scrollbars=yes,resizable=yes,location=no');
  w.location=l; // handle#a
};

// Given an Id, get back the text value in that tag element.  Remember to set up id="something" rather than name="something"
function getElementHTML(inElementId) {
   var valueText = '';
   if (document.getElementById(inElementId)) {
      valueText = document.getElementById(inElementId).innerHTML;
   }
   return valueText;
}; // getElementHTML

function getElement(inElementId) {
   if (document.getElementById(inElementId)) {
      return document.getElementById(inElementId);
   }
   else {
      return null;
   }
}; // getElement

// Given an Id, set display = none
function hideElement(inElementId) {
   if (document.getElementById(inElementId)) {
      document.getElementById(inElementId).style.display = 'none';
   }
}; // hideElement

// Given an Id, set display = inline
function showElement(inElementId) {
   if (document.getElementById(inElementId)) {
      getElement(inElementId).style.display = 'inline';
   }
}; // showElement

// given a dropdown with inddId set value to inValue
function setSelectedDD(inddId, inValue) {
   var inDD = getElement(inddId);
   if ((inDD) && (inDD.options.length > 0)) {
      for (var j = 0; j < inDD.options.length; j++) {
         if (inDD.options[j].value.match(inValue, "i")) {
            inDD.options[j].selected = true;
            break;
         }
      }
   }
}; // setSelectedDD

// get selected value of dropdown inddId
function selectValue(inddId) {
   var inDD = getElement(inddId), outValue = '';
   if (inDD) {
      outValue = inDD.options[inDD.selectedIndex].value;
   }
  return outValue;
};

// Function to process Google Books info and update the dom
function ProcessGBSBookInfo(booksInfo) {
  // Don't display for MARC format
  if (queryString('format') != '001') {

   for (isbn in booksInfo) {
      var url_elem = document.getElementById(isbn);
//      var pic_elem = document.getElementById("google_book");
      var bookInfo = booksInfo[isbn];
      if (bookInfo && url_elem) {
         url_elem.href = 'javascript:cclaWindow(\'' + bookInfo.info_url + '\',\'googleinfo\')';
         url_elem.style.display = '';
/*         if (bookInfo.thumbnail_url && pic_elem) {
            pic_elem.src = bookInfo.thumbnail_url;
            pic_elem.style.display = '';
         }
*/
      }
   }
  }
};

/*
 Given a string in format of sublibrary~collection~callnumber (of some delim), splits and formats string
 adding to table cells, passing back.  Looks for audio and ebooks as well
 In:
    outURLStr: The link to the location
    inLocStr: The Text to parse
    delimVal: The delimiter used for separating the locations
*/
function splitLocStr(outURLStr, inLocStr, delimVal) {
   var outStr = '', location = '', collection = '', callNumber = '', isEABook = false;
   outStr += '<tr><td align="left">';
   var testRE = new RegExp(delimVal, "i");
   var textList = inLocStr.split(testRE);

   if (textList.length > 0) { location = textList[0]; }
   if (textList.length > 1) { collection = textList[1]; }

   // want all to the right of and including call number, but get rid of delim
   var connector = '';
   for (j = 2; j < textList.length; j++) {
      callNumber += connector + textList[j];
      connector = ' ';
   }

   var eRegEx = /ebooks|eaudiobook(s)?|Free eBooks|web resources|Electronic Video|emusic/i;
   if (eRegEx.test(collection))
   {
      isEABook = true;
      outStr += '<a href="javascript:cclaWindow(\'';
      if (collection.match(/Free eBooks/i)) {
         collection = 'eBooks';
         outStr += callNumber;
      } else if (collection.match(/web resources/i)) {
         collection = 'Web Resources';
         outStr += callNumber;
      } else {
         outStr += 'http://www.linccweb.org/webscripts/ebooks.asp?bookid=' + callNumber;
      }
      outStr += '\',\'' + collection.replace(/\s|&nbsp;/i, '') + '\')" title="Preview ';

      eRegEx = /ebooks/i;
      if (eRegEx.test(collection))
      {
         outStr += 'eBook';
      }
      else
      {
         eRegEx = /Electronic Video/i;
         if (eRegEx.test(collection)) {
            outStr += 'Electronic Video';
         } else {
            outStr += 'Audiobook';
         }
      }
      outStr += '">' + location + '</a>' + '</td><td align="left">' + collection + '</td><td></td>';
   } else {
      outStr += '<a href="' + outURLStr + '" title="' + location + '">' + location + '</a>' + '</td><td align="left">' + collection + '</td><td align="left">' + callNumber + '</td>';
   }
   outStr += '</tr>'
   return outStr
}; // end splitLocStr

// sets cookie with optional parameters name, value, expiration year, expiration month, expiration day, path, domain, secure
function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
  var cookie_string = '';
  cookie_string = name + "=" + escape(doSecure(  value ));
  domain = ".linccweb.org"

  if ( exp_y )
  {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }

  if ( path )
        cookie_string += "; path=" + escape ( path );

  if ( domain )
        cookie_string += "; domain=" + escape ( domain );
  
  if ( secure )
        cookie_string += "; secure";
  
  document.cookie = cookie_string;
}; // set_cookie

// delete cookie name passed in.
function delete_cookie ( cookie_name )
{
  // first clear cookie because it might stick around
  set_cookie(cookie_name,'','','','','','','') 
  var cookie_date = new Date ( );  // current date & time
  cookie_date.setTime ( cookie_date.getTime() - 1 );
  document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}; // delete_cookie

// get the cookie value for name passed in
function get_cookie ( cookie_name, secure )
{
   var results = document.cookie.match ( cookie_name + '=(.*?)(;|$)' );

   if ( results ) {
      return doUnsecure( unescape(results[1]) );
   } else {
      return null;
   }
}; // get_cookie

// Common function used to change to the ILL request (and handle nonpart libraries)
function goToILL(inLW, inSopac, borid, borver, borlib, doclib, docnum) {
   var nonpart = 'OWC50';
   if (nonpart.indexOf(borlib) > -1) {
      top.location= inLW + '/ill/request.asp'
         + '?b=' + borid
         + '&p=' + borver
         + '&l=' + borlib
         + '&doc_library=' + doclib
         + '&doc_number=' + docnum;
   } else {
      top.location= inSopac + '?func=new-ill-request-l'
         + '&doc_library=' + doclib
         + '&doc_number=' + docnum
         + '&bor_id=' + borid
         + '&bor_verification=' + borver
         + '&bor_library=' + borlib;
   } 
}; // goToILL 

// Given a session, func, the start string, and the begin number, end number, and total number
// and the padding length
// Create the previous and next links
function writePrevNextFunc(inSession, inFunc, startStr, inBegNum, inEndNum, inTotalNum, padLength) {
   var begNum = parseInt(inBegNum)
   var endNum = parseInt(inEndNum)
   var totalNum = parseInt(inTotalNum)
   document.write('<div style="width:750px;text-align:left;" class="noprint">');
   document.write('<table style="width:180px;" border="0" cellspacing="2" class="noprint">');
   document.write('<tr><td style="text-align:left;">');
   if ((inSession == '') || (inFunc == '')) {
      document.write('<br></td><td><br></td>');
   } else {
      if ((begNum == '') || (begNum == '1')) {
         document.write('<br>');
      } else {
         document.write('<div style="width:90px;text-align:center;" class="cclabmed">');
         document.write('<a style="width:100%;display:block;" class="cclabmed" href="'); 
         document.write(inSession + '?func=' + inFunc + '&' + startStr + '=' + padLeft(Math.max(1, begNum - 20) + '', padLength, '0'));
         document.write('" title="Go to Previous List">Previous</a>');
         document.write('</div>');
      }
      document.write('</td><td style="text-align:left;">');
      if ((endNum == '') || (endNum == totalNum)) {
         document.write('<br>');
      } else {
         document.write('<div style="width:90px;text-align:center;" class="cclabmed">');
         document.write('<a style="width:100%;display:block;" class="cclabmed" href="');
         document.write(inSession + '?func=' + inFunc + '&' + startStr + '=' + padLeft(Math.min(endNum + 1, totalNum) + '', padLength, '0'));
         document.write('" title="Go to Next List">Next</a>');
         document.write('</div>');
      }
      document.write('</td>');
   }
   document.write('</tr></table></div>');
}

// Given an href and a type, write the previous/next links
// inType = 'prev' or 'next'
function writePrevNext(prevURL, nextURL) {
   var prevPage = getNavLink(prevURL);
   var nextPage = getNavLink(nextURL);
   var prevNextVisible = (prevPage != '' || nextPage != '')?'inline':'none';
   document.write('<div style="width:750px;text-align:left;display:' + prevNextVisible + '" class="noprint">');
   document.write('<table style="width:180px;" border="0" cellspacing="2" class="noprint">');
   document.write('<tr><td style="text-align:left;">');
   if (prevPage != '') {
      document.write('<div style="width:90px;text-align:center;" class="cclabmed">');
      document.write('<a style="width:100%;display:block;" class="cclabmed" href="' + prevPage + '" title="Go to Previous List">Previous</a>');
      document.write('</div>');
   } else {
      document.write('<br>');
   }
   document.write('</td><td style="text-align:left;">');
   if (nextPage != '') {
      document.write('<div style="width:90px;text-align:center;" class="cclabmed">');
      document.write('<a style="width:100%;display:block;" class="cclabmed" href="' + nextPage + '" title="Go to Next List">Next</a>');
      document.write('</div>');
   } else {
      document.write('<br>');
   }
   document.write('</td></tr></table></div>');
}; // writePrevNext

// This will logout if window closed
function doUnload(event) {
//   if (isCloseEvent(event)) {
//      var newLoc = unescape(window.location.href);
//      newLoc = newLoc.substring(0,newLoc.indexOf('func')) + 'func=logout';
//      window.location.href = newLoc;
//   }
}; // doUnload

// Save the encrypted borid, ver, and lib
function saveLICookies() {
   var borId = '', borVer = '', borLib = '';
   borId = getElement("bor_id").value;
   borVer = getElement("bor_verification").value;
   borLib = getElement("bor_library").value;
   set_cookie('bid', borId, '', '', '', '', '', '');
   set_cookie('bve', borVer, '', '', '', '', '', '');
   set_cookie('bor_library', borLib, '', '', '', '', '', '');
}; // saveLICookies

//------------------------------------------------------------------------------
/* Original:  Tomislav Sereg (tsereg@net.hr)
    Web Site:  http://www.inet.hr/~tsereg/jse

    This script and many more are available free online at
    The JavaScript Source!! http://javascript.internet.com
*/
function permutationGenerator(nNumElements) {
this.nNumElements     = nNumElements;
this.antranspositions = new Array;
var k = 0;
for (i = 0; i < nNumElements - 1; i++)
for (j = i + 1; j < nNumElements; j++)
this.antranspositions[ k++ ] = ( i << 8 ) | j;
// keep two positions as lo and hi byte!
this.nNumtranspositions = k;
this.fromCycle = permutationGenerator_fromCycle;
}
function permutationGenerator_fromCycle(anCycle) {
var anpermutation = new Array(this.nNumElements);
for (var i = 0; i < this.nNumElements; i++) anpermutation[i] = i;
for (var i = 0; i < anCycle.length; i++) {
var nT = this.antranspositions[anCycle[i]];
var n1 = nT & 255;
var n2 = (nT >> 8) & 255;
nT = anpermutation[n1];
anpermutation[n1] = anpermutation[n2];
anpermutation[n2] = nT;
}
return anpermutation;
}
function password(strpasswd) {
this.strpasswd = strpasswd;
this.getHashValue   = password_getHashValue;
this.getpermutation = password_getpermutation;
}
function password_getHashValue() {
var m = 907633409;
var a = 65599;
var h = 0;
for (var i = 0; i < this.strpasswd.length; i++) 
h = (h % m) * a + this.strpasswd.charCodeAt(i);
return h;
}
function password_getpermutation() {
var nNUMELEMENTS = 13;
var nCYCLELENGTH = 21;
pg = new permutationGenerator(nNUMELEMENTS);
var anCycle = new Array(nCYCLELENGTH);
var npred   = this.getHashValue();
for (var i = 0; i < nCYCLELENGTH; i++) {
npred = 314159269 * npred + 907633409;
anCycle[i] = npred % pg.nNumtranspositions;
}
return pg.fromCycle(anCycle);
}
function SecureContext(strText, strSignature, bEscape) {
this.strSIGNATURE = strSignature || '';
this.bESCApE      = bEscape || false;
this.strText = strText;
this.escape        = SecureContext_escape;
this.unescape      = SecureContext_unescape;
this.transliterate = SecureContext_transliterate;
this.encypher      = SecureContext_encypher;
this.decypher      = SecureContext_decypher;
this.sign          = SecureContext_sign;
this.unsign        = SecureContext_unsign;
this.secure   = SecureContext_secure;
this.unsecure = SecureContext_unsecure;
}
function SecureContext_escape(strToEscape) {
var strEscaped = '';
for (var i = 0; i < strToEscape.length; i++) {
var chT = strToEscape.charAt( i );
switch(chT) {
case '\r': strEscaped += '\\r'; break;
case '\n': strEscaped += '\\n'; break;
case '\\': strEscaped += '\\\\'; break;
default: strEscaped += chT;
   }
}
return strEscaped;
}
function SecureContext_unescape(strToUnescape) {
var strUnescaped = '';
var i = 0;
while (i < strToUnescape.length) {
var chT = strToUnescape.charAt(i++);
if ('\\' == chT) {
chT = strToUnescape.charAt( i++ );
switch( chT ) {
case 'r': strUnescaped += '\r'; break;
case 'n': strUnescaped += '\n'; break;
case '\\': strUnescaped += '\\'; break;
default: // not possible
   }
}
else strUnescaped += chT;
}
return strUnescaped;
}
function SecureContext_transliterate(btransliterate) {
var strDest = '';

var nTextIter  = 0;
var nTexttrail = 0;

while (nTextIter < this.strText.length) {
var strRun = '';
var cSkipped   = 0;
while (cSkipped < 7 && nTextIter < this.strText.length) {
var chT = this.strText.charAt(nTextIter++);
if (-1 == strRun.indexOf(chT)) {
strRun += chT;
cSkipped = 0;
}
else cSkipped++;
}
while (nTexttrail < nTextIter) {
var nRunIdx = strRun.indexOf(this.strText.charAt(nTexttrail++));
if (btransliterate) {
nRunIdx++
if (nRunIdx == strRun.length) nRunIdx = 0;
}
else {
nRunIdx--;
if (nRunIdx == -1) nRunIdx += strRun.length;
}
strDest += strRun.charAt(nRunIdx);
   }
}
this.strText = strDest;
}
function SecureContext_encypher(anperm) {
var strEncyph = '';
var nCols     = anperm.length;
var nRows     = this.strText.length / nCols;
for (var i = 0; i < nCols; i++) {
var k = anperm[ i ];
for (var j = 0; j < nRows; j++) {
strEncyph += this.strText.charAt(k);
k         += nCols;
   }
}
this.strText = strEncyph;
}
function SecureContext_decypher(anperm) {
var nRows    = anperm.length;
var nCols    = this.strText.length / nRows;
var anRowOfs = new Array;
for (var i = 0 ; i < nRows; i++) anRowOfs[ anperm[ i ] ] = i * nCols;
var strplain = '';
for (var i = 0; i < nCols; i++) {
for (var j = 0; j < nRows; j++)
strplain += this.strText.charAt(anRowOfs[ j ] + i);
}
this.strText = strplain;
}
function SecureContext_sign(nCols) {
if (this.bESCApE) {
this.strText      = this.escape(this.strText);
this.strSIGNATURE = this.escape(this.strSIGNATURE);
}
var nTextLen     = this.strText.length + this.strSIGNATURE.length;
var nMissingCols = nCols - (nTextLen % nCols);
var strpadding   = '';  
if (nMissingCols < nCols)
for (var i = 0; i < nMissingCols; i++) strpadding += ' ';
var x = this.strText.length;
this.strText +=  strpadding + this.strSIGNATURE;
}
function SecureContext_unsign(nCols) {
if (this.bESCApE) {
this.strText      = this.unescape(this.strText);
this.strSIGNATURE = this.unescape(this.strSIGNATURE);
}
if ('' == this.strSIGNATURE) return true;
var nTextLen = this.strText.lastIndexOf(this.strSIGNATURE);
if (-1 == nTextLen) return false;
this.strText = this.strText.substr(0, nTextLen);
return true;
}
function SecureContext_secure(strpasswd) {
var passwd = new password(strpasswd);
var anperm   = passwd.getpermutation()
this.sign(anperm.length);
this.transliterate(true);
this.encypher(anperm);
}
function SecureContext_unsecure(strpasswd) {
var passwd = new password(strpasswd);
var anperm = passwd.getpermutation()
this.decypher(anperm);
this.transliterate(false);
return this.unsign(anperm.length);
}

function doSecure(inUnsecStr) {
var sc = new SecureContext(inUnsecStr, '', false);
sc.secure('8675309');
return sc.strText;
}

function doUnsecure(inSecStr) {
var sc = new SecureContext(inSecStr, '', false);
if (!sc.unsecure('8675309')) 
alert('Invalid password used.');
return sc.strText;
}
