// --------------------- Cookie Access Functions ---------------------

// Delete a cookie having a specific name, and optional path and domain.
function deleteCookie (name, path, domain) {

	if (GetCookie(name)) {
	
		document.cookie = name + "=" +
			((path) ? "; path=" + path : "") +
			((domain) ? "; domain=" + domain : "") +
			"; expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
}

// ----------------------- Login Authorization -----------------------

// Verify that all required account login identification data has been entered.
function verifyLoginInfo(curform) {

	for (var x = 0; x < curform.length; x++) {

		if (curform.elements[x].value.length < 1) {
			
			var err = "All fields are required to determine your account.\n\n" +
				"Please enter missing information.";
			alert(err);
			
			curform.elements[x].focus();
			
			return false;
		}
	}
	
	// Return true to allow the submit action.
	return true;
}

// Set focus to the form's first input prompt.
function initFocus() {
	document.forms[0].elements[0].focus();
}

// ---------------------- Window Open Functions ----------------------

// Initialize global window open variables.
if (window.opener) NewWin = window.opener; else NewWin = "";
if (NewWin && NewWin.name) TargetWindow = NewWin.name; else TargetWindow = "";

// Open a popup Window to a specified URL, with a target name and
// specific window display features.
function openWin(winURL, winName, winFeatures) {
	
	alert (winName);
	if (parent.frames[winName]) {
		parent.frames[winName].location.href = winURL;
		return;
	}

	if (winFeatures)
		NewWin = window.open(winURL, (winName?winName:""), winFeatures);
	else
		NewWin = window.open(winURL, (winName?winName:""));
 
 	if (NewWin != null) {

		if (NewWin.focus != null) NewWin.focus();

		if (!NewWin.opener) NewWin.opener = window;
		if (!NewWin.opener.name) NewWin.opener.name = "theopener";
	}
}

// Open the authorized links window with a defaultable URL.
function openLinksWin(curURL) {
	var theURL = (curURL) ? curURL : "authlink.htm";
	openWin(theURL, 'main');
}

// -------------------- Window Timeout Functions ---------------------

// Initialize global timeout variables.
DefaultSeconds = 1200;
TimeoutSeconds = DefaultSeconds;

// Eliminate the current window's authorization and reload index.htm
function logout() {
	deleteCookie("auths");
	deleteCookie("auths","/");

	deleteCookie("pData");
	deleteCookie("pData", "/");

	deleteCookie("libCode");
	deleteCookie("libCode", "/");

	deleteCookie("resources");
	deleteCookie("resources","/");

	top.location="http://rpa.ci.north-platte.ne.us";
}

// reset authorization timeout
function resetAuth() {

   	resetCookieExpire("auths");
   	resetCookieExpire("auths","/");
	resetCookieExpire("pdata");
	resetCookieExpire("pdata","/");
	resetCookieExpire("libCode");
	resetCookieExpire("libCode","/");
	resetCookieExpire("resources");
	resetCookieExpire("resources","/");
	resetCookieExpire("expTime");
	resetCookieExpire("expTime","/");
}

function resetCookieExpire(name,path,domain) {
	TimeoutSeconds = GetCookie("expTime");
	var expdate = new Date ();
	FixCookieDate (expdate); // Correct for Mac date bug
	expdate.setTime (expdate.getTime() + (TimeoutSeconds * 1000));
	
    tmpValue = GetCookie(name);
	if (tmpValue)
	   SetCookie (name,tmpValue,expdate, path,domain);
}

// --------------------- Window Links Functions ----------------------

// Open a link in the current main target window.
function go(curURL, newtarget) {
	resetAuth();
}

// URL unencode a given string including "+" to " " restoration.
function URLdecode(str) {
	var out = unescape(str);
	var pos;

	// Loop to remove each "+" found.
	while ((pos = out.indexOf("+")) != -1)
		out = out.substring(0,pos) + " " + out.substring(pos+1);
	return out;
}

// Create a set of authorized hyperlinks with window open targeting.
function buildLinks() {
	var linksValue = GetCookie("auths");
	var curLink, curDesc, curURL, str, pos, pos2;
	if (!linksValue || linksValue.length < 0) {
		document.write("<H3>No Authorized Links</H3>");
		return false;
	}

	while ((pos = linksValue.indexOf("__")) != -1) {
		curLink = linksValue.substring(0,pos);
		linksValue = linksValue.substring(pos+2);

		if (curLink.length) {
			pos2 = curLink.indexOf("^");
			curDesc = URLdecode(curLink.substring(0,pos2));
			curURL = "/rpa/webauth.exe?rs=" + URLdecode(curLink.substring(pos2+1) + "&fr=1");

			str = '<A HREF="'+curURL+'" TARGET="feature" onClick="resetAuth();" onMouseover="window.status='+"' '"+'; return true;" onMouseout="window.status='+"' '"+'; return true;">' + curDesc + '</A><BR>';
			document.writeln(str);
		}
	}
	return true;
}

function getclienttime() {
// returns the current time on the client in seconds elapsed since 01/01/1970
// value is returned in the ct variable which is a hidden input to be read by CGI
	var curTime = new Date ();
	document.search.ct.value = Math.round(curTime.getTime()/1000);
//	alert(document.search.ct.value);
}

//
//  Function to create or update a cookie.
//    name - String object containing the cookie name.
//    value - String object containing the cookie value.  May contain
//      any valid string characters.
//    [expires] - Date object containing the expiration data of the cookie.  If
//      omitted or null, expires the cookie at the end of the current session.
//    [path] - String object indicating the path for which the cookie is valid.
//      If omitted or null, uses the path of the calling document.
//    [domain] - String object indicating the domain for which the cookie is
//      valid.  If omitted or null, uses the domain of the calling document.
//    [secure] - Boolean (true/false) value indicating whether cookie transmission
//      requires a secure channel (HTTPS).  
//
//  The first two parameters are required.  The others, if supplied, must
//  be passed in the order listed above.  To omit an unused optional field,
//  use null as a place holder.  For example, to call SetCookie using name,
//  value and path, you would code:
//
//      SetCookie ("myCookieName", "myCookieValue", null, "/");
//
//  Note that trailing omitted parameters do not require a placeholder.
//
//  To set a secure cookie for path "/myPath", that expires after the
//  current session, you might code:
//
//      SetCookie (myCookieVar, cookieValueVar, null, "/myPath", null, true);
//
function SetCookie (name,value,expires,path,domain,secure) {
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

//
//  Function to correct for 2.x Mac date bug.  Call this function to
//  fix a date object prior to passing it to SetCookie.
//  IMPORTANT:  This function should only be called *once* for
//  any given date object!  See example at the end of this document.
//
function FixCookieDate (date) {
  var base = new Date(0);
  var skew = base.getTime(); // dawn of (Unix) time - should be 0
  if (skew > 0)  // Except on the Mac - ahead of its time
    date.setTime (date.getTime() - skew);
}

//
//  Function to return the value of the cookie specified by "name".
//    name - String object containing the cookie name.
//    returns - String object containing the cookie value, or null if
//      the cookie does not exist.
//
function GetCookie (name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
      return getCookieVal (j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break; 
  }
  return null;
}
// "Internal" function to return the decoded value of a cookie
//
function getCookieVal (offset) {
  var endstr = document.cookie.indexOf (";", offset);
  if (endstr == -1)
    endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}

// Gets patron name from cookie if it exists otherwise returns null
function getPName(curname) {
	var str = curname + "=";
	var slen = str.length;
	var clen = document.cookie.length;
	var pName = "";

	// Check if there are any cookies.
	if (clen > 0) {

		// Check if the named cookie exists.
		offset = document.cookie.indexOf(str);
		if (offset != -1) {

			// Get the position of the beginning of the cookie value.
			offset += slen;

			// Get the position of the end of the patron name.
			endpos = document.cookie.indexOf("%7C", offset);
			if (endpos == -1) endpos = clen;

			// Extract and return the cookie value substring decoded.
			pName = document.cookie.substring(offset, endpos);
                  while ((pos = pName.indexOf("+")) != -1)
                     pName = pName.substring(0,pos) + " " + pName.substring(pos+1);
                  while ((pos = pName.indexOf("%")) != -1)
                  {
                     if (pName.substring(pos+1,pos+3) == "2E")
                        // period
                        pName = pName.substring(0,pos) + "&#46" + pName.substring(pos+3);
                     else if (pName.substring(pos+1,pos+3) == "2D")
                        // hyphen
                        pName = pName.substring(0,pos) + "&#45" + pName.substring(pos+3);
                     else if (pName.substring(pos+1,pos+3) == "27")
                        // apostrophe
                        pName = pName.substring(0,pos) + "&#39" + pName.substring(pos+3);
                    else
                        // strip out
                        pName = pName.substring(0,pos) + pName.substring(pos+1);
                  }

			// Extract and return the cookie value patron name.
			return pName;
		} 
	}

	// Default to return null if the cookie was not found.
	return null;
}
