/* ------------------------------------------------------------ 
   Copyright (c) 2006 ManyFutures, Inc. All rights reserved.
   ------------------------------------------------------------ 
   FILE: ethiopia.js
   DESCRIPTION: Site wide javascript functions for gpf.
   We try to place all (most) javascript into one file that will
   be downloaded once and cached for all pages.
   ------------------------------------------------------------ */

/* ********************* MAIN ONLOAD ** MAIN ONLOAD ***************** */
/* ********************* MAIN ONLOAD ** MAIN ONLOAD ***************** */
/* ********************* MAIN ONLOAD ** MAIN ONLOAD ***************** */

/*
 * This is the main onload function that will call others
 */

function pageOnLoad() {
//   alert('The cobrand is :'+getCobrandFromURL());
   //tableHeight();
   startList();
   maskPasswordInput();
   //grabRefCode();
   checkLogin();	// this lives in ggajax.js
   // Look for queued up Listener functions to call, now that page is loaded
   if (window.onloadListeners)
   {
   for (var i=0;i < window.onloadListeners.length;i++) 
   {
   var func=window.onloadListeners[i];
   func.call();
   }
   }
}



/* ********************* GENERAL ** GENERAL ***************** */
/* ********************* GENERAL ** GENERAL ***************** */
/* ********************* GENERAL ** GENERAL ***************** */

/* Set an numeric table height for spacer column */
function tableHeight() {
  var yTop = 20;
  var yBottom = 20;
  alert (document.getElementById("td1").offsetHeight);
  var td_height = (document.getElementById("td1").offsetHeight - (yTop + yBottom));
  alert (td_height);
  var table_height = document.getElementById("table1");
  table_height.setAttribute("height",td_height);
}


/*
 * Function called on every page to check if the user is logged in 
 * or not.  If they are logged, we display their display name, handed 
 * to me by the cookie.
 */

/* To be implemented along with sign in */

function welcomemsg() 
{
    var andthen_login  = '&andthen=' + escape('/');
    var andthen_logout = '&andthen=' + escape('/dy/login/gap.html?cmd=login&andthen=/');

    var href_login  = ' href="/dy/login/gap.html?cmd=login'
                      + andthen_login + '" ';
    var href_logout = ' href="/dy/login/gap.html?cmd=logout'
                      + andthen_logout + '" ';

    var test = document.cookie.indexOf('ggUserName=')
    if (test > -1) 
    {
        var begin = document.cookie.indexOf('ggUserName=')+18;
	var end = document.cookie.indexOf(';',test);
	if (end < 0) {
	    var end = document.cookie.length;
	}
	var cookieval = document.cookie.substring(begin,end);
        var scv = cookieval.replace(/\s/g, '&nbsp;');
        document.write('<a class="nav_title_bar" '
			+ href_logout
                        + ' ><b>Welcome&nbsp;' + scv 
                        + '&nbsp;-&nbsp;Logout</b></a>');
    }
    else {
	    document.write('<a class="nav_title_bar" '
                           + href_login
                           + ' ><b>Welcome&nbsp;Guest&nbsp;-&nbsp;Login</b></a>');
    }
}



// Show the registry bells icon if a registry is present.
function registrybells(projid)
{
  if( document.cookie.indexOf('currentRegistry=') > -1 ) {
    document.write('<a href="/dy/registry/gap.html?cmd=helpadd&projid=' + projid + '"><img alt="bells" border="0" src="img/bells_trans.gif"></a>');
  }
}



// Popup a help window
function showhelp(url)
{
  var width = 400;
  var height = 500;
  var name = 'HelpWindow';
  settings="toolbar=no,location=no,directories=no,"
    + "status=no,menubar=no,scrollbars=yes,resizable=no,"
    + "width=" + width + ",height=" + height;
  window.open(url,name,settings);
}



/**
 * this determines a cobrand id from the location path
 * NOTE: if cobrand id is cidi, this returns gg 
 * Because this is used to determine cookie names for login tokens
 * And gg and CIDI want to share a common login
 * All other cobrands have individual login.
 * TODO:  Need to implement special code for cobrands that
 * have their own URL (ie. not globalgiving/cb/<cbid>
 */
function getCobrandFromURL()
{
   var result = 'gap';
   var path = location.pathname;
   if (path==null || path.length < 3)
   {
      if (location.hostname.indexOf("gap") > -1) return result;
      // else its a different URL/cobrand, figure it out!!!
   }
   else
   {
		if (path.indexOf("/dy/v2/admin/") > -1) {
			var re = "dy\\/v2\\/admin\\/[^\\/]+\\/";
			var matches = path.match(re);
			if (matches != null && matches.length == 1)
				result = matches[0].substring(12, matches[0].length - 1);
			else
				result = 'gap';
		}
		else if (path.indexOf("/dy/") > -1)
      {
         // find the html portion
         var re = /(\/.*)+\/(.+)\.html/;
         var matches = path.match(re);
         if (matches != null && matches.length > 2) {
            result = matches[2];
         }
      }
      else if (path.indexOf("/cb/") > -1)
      {
         // find the cb in path
         var re = /\/cb\/(\w+)\//;
         var matches = path.match(re);
         result = matches[1];
      }
      if (result == 'gap') result = 'gap'; // gap and gg are the same!!
      return result;
   }
}



/* ********************* COOKIES CHECK FOR LOGIN BOX ****************** */
/* ********************* COOKIES CHECK FOR LOGIN BOX ****************** */
/* ********************* COOKIES CHECK FOR LOGIN BOX ****************** */

/*

DISCLAIMER: THESE JAVASCRIPT FUNCTIONS ARE SUPPLIED 'AS IS', WITH 
NO WARRANTY EXPRESSED OR IMPLIED. YOU USE THEM AT YOUR OWN RISK. 
NEITHER PAUL STEPHENS NOR PC PLUS MAGAZINE ACCEPTS ANY LIABILITY FOR 
ANY LOSS OR DAMAGE RESULTING FROM THEIR USE, HOWEVER CAUSED. 

Paul Stephens' NetScape-based cookie-handling library

http://web.ukonline.co.uk/paul.stephens/index.htm

TO USE THIS LIBRARY, INSERT ITS CONTENTS IN A <script></script> BLOCK IN THE 
<HEAD> SECTION OF YOUR WEB PAGE SOURCE, BEFORE ANY OTHER JAVASCRIPT ROUTINES.

Feel free to use this code, but please leave this comment block in.

*/

function setCookie (name, value, lifespan, access_path) {
      
  var cookietext = name + "=" + escape(value)  
    if (lifespan != null) {  
      var today=new Date()     
      var expiredate = new Date()      
      expiredate.setTime(today.getTime() + 1000*60*60*24*lifespan)
      cookietext += "; expires=" + expiredate.toGMTString()
    }
    if (access_path != null) { 
      cookietext += "; PATH="+access_path 
    }
   document.cookie = cookietext 
   return null  
}


function setDatedCookie(name, value, expire, access_path) {
    var cookietext = name + "=" + escape(value)
      + ((expire == null) ? "" : ("; expires=" + expire.toGMTString()))
     if (access_path != null) { 
      cookietext += "; PATH="+access_path 
     }
   document.cookie = cookietext 
   return null        
}

/**
 * Get the value of a cookie.  If the cookie does not exist, return 'null'.
 *
 * Use this function instead of 'getCookie()' as this function is more
 * appropriately/accurately named.
 */
function getCookieValue( Name ) {
  var search = Name + "="                       
  var CookieString = document.cookie            
  var result = null                               
  if (CookieString.length > 0) {                
    offset = CookieString.indexOf(search)       
    if (offset != -1) {                         
      offset += search.length                   
      end = CookieString.indexOf(";", offset)   
      if (end == -1)                            
        end = CookieString.length;               
      result = decodeURIComponent(CookieString.substring(offset, end));
                                                
      } 
    }
   return result;                                
}

/** 
 * Check if a cookie exists at all.  Value may still be blank (i.e. an empty
 * string).  Function returns a boolean - true if the cookie exists; otherwise,
 * false.
 */
function userHasCookie( CookieName ) {
  var cookieValue = getCookieValue( CookieName )
  if ( cookieValue == null ) return false
  return true
}

/**
 * This function should really be called getCookieValue(), because it returns
 * a cookie's value, not a cookie object itself.
 */
function getCookie( Name ) {
  return getCookieValue( Name )
}


/**
 * Remove a cookie.
 */
function deleteCookie(Name, Path) {
  setCookie(Name,"Deleted", -1, Path)
}



/* ********************* VALUE OUTCOMES ***************** */
/* ********************* VALUE OUTCOMES ***************** */
/* ********************* VALUE OUTCOMES ***************** */

function getVOVariable() {
var name_value = getVOValue("vo");
var name_value_other = getVOValue("amount");
}

function getVOValue(varname) {
  // First, we load the URL into a variable
  var url = window.location.href;

  // Next, split the url by the ?
  var qparts = url.split("?");

  // Check that there is a querystring, return "" if not
  if (qparts.length == 0)
  {
    return "";
  }

  // Then find the querystring, everything after the ?
  var query = qparts[1];

  // Split the query string into variables (separates by &s)
  var vars = query.split("&");

  // Initialize the value with "" as default
  var value = "";

  // Iterate through vars, checking each one for varname
  for (i=0;i<vars.length;i++)
  {
    // Split the variable by =, which splits name and value
    var parts = vars[i].split("=");
	
    // Check if the correct variable
    if (parts[0] == varname)
    {
      // Load value into variable
      value = parts[1];
	  
      // End the loop
      break;
    }
  }
  
  // Convert escape code
  value = unescape(value);

  // Convert "+"s to " "s
  // value.replace(/\+/g," ");

  // Return the value
  return value;
}

function focusTextBox(form) {
	form.amount.focus();
}

function clearTextBox(form) {
	if (form && form.amount) {
		form.amount.value = '';
	}
}
function validateAmt(myform, elementId) {
	if (!validateNumber(myform.amount, false, 'Donation amount', true, 0, 10,
			10000)) {
		myform.amount.select();

		if (document.getElementById(elementId)) {
			if (myform.amount > 10000) {
				document.getElementById(elementId).innerHTML = "Gift cards must be less than $10,000.";
			} else {
				document.getElementById(elementId).innerHTML = "Gift cards must be at least $10.";
			}
		}
		setTimeout( function() {
			myform.amount.focus()
		}, 10);
		return false;
	} else
		return true;
}

function validateOtherAmt(f) {
	if (f.vo_id.value == -1) // validate amount?
	{
		var x = f.amount.value
		x = x.replace(",", "");
		var anum = /(^\d+$)|(^\d+\.\d+$)/
		if (anum.test(x)) {
			// alert("pass test numeric");
		} else {
			// alert("fail test numeric");
			alert("Donation amount must be a whole number greater than US $10.");
			f.amount.value = '';
			f.amount.focus();
			return false;
		}
		if (x >= 10) {
			// alert("pass test >= 10");
		} else {
			// alert("fail test >= 10");
			alert("Donation amount must be a whole number greater than US $10.");
			setTimeout( function() {
				f.amount.focus()
			}, 10);
			f.amount.focus();
			return false;
		}
	}
	return true;
}



/* ********************* EMAIL ** EMAIL ***************** */
/* ********************* EMAIL ** EMAIL ***************** */
/* ********************* EMAIL ** EMAIL ***************** */

/*
 * Functions used to mask email addresses throughout website.
 * Variations on subject line, body or email address style
 */

function mkaddr5(addr,subj,body,label) {
  document.write('<a class="menutab" href=\"mailto:' + addr + '@' + site 
	+ '?subject=' + subj + '&body=' + body + '\">' 
	+ label + '</a>');
}

function mkaddr4(addr,subj,body,label) {
  site = "globalgiving.com";
  document.write('<a href=\"mailto:' + addr + '@' + site 
	+ '?subject=' + subj + '&body=' + body + '\">' 
	+ label + '</a>');
}

function mkaddr2(addr,label) {
  site = "globalgiving.com";
  document.write('<a class="footer" href=\"mailto:' + addr + '@' + site 
        + '\">' + label + '</a>');
}

function mkaddr_nav(addr,label) {
  site = "globalgiving.com";
  document.write('<a class="nav_title" href=\"mailto:' + addr + '@' + site 
        + '\">' + label + '</a>');
}

function mkaddrimg(addr) {
  site = "gapgiving.org";
  document.write('<a href=\"mailto:' + addr + '@' + site + '"'
        + 'OnMouseOver=\"document.cu.src=\'/cb/gap/img/contact_us_over.gif\'\"' + 'OnMouseOut=\"document.cu.src=\'/cb/gap/img/contact_us.gif\'\">' + '<img src="/cb/gap/img/contact_us.gif" align="middle" name="cu" border="0" style="margin-bottom: 30px;">' + '</a>');
}

function mkaddr(addr) {
  site = "globalgiving.com";
  mkaddr2(addr,addr + '@' + site);
}

function mkaddrET(addr) {
  site = "globalgiving.com";
  mkaddr2(addr,addr + '@' + site);
}

function protectaddr(addr,domain,label) {
	document.write('<a class="footer" href=\"mailto:' + addr + '@' + domain 
		+ '\">' + label + '</a>');
}

function protectaddr2(addr,domain) {
	document.write('<a href=\"mailto:' + addr + '@' + domain 
		+ '\">' + addr + '@' + domain + '</a>');
}
 

function emailafriend(subject,body,url,lbl) {
    document.write('<a href="mailto:?subject='+subject+'&body='+body+'  See more details and give directly to this project at http://www.gapgiving.org/'+url+'">'+lbl+'</a>');
}


function emailprofile(subject,body,url,lbl) {
    document.write('<a class="footer" href="mailto:?subject=' + subject + '&body=' + body + escape(url) + ' ">'+lbl+'</a>');
}



/* ********************* POP UPS * POP UPS ***************** */
/* ********************* POP UPS * POP UPS ***************** */
/* ********************* POP UPS * POP UPS ***************** */

/*
 * Functions that call up a pop-up window.  Settings vary for new window.
 */

// Simple browser window without features
function popup(url, name, width, height) {
  settings=
  "toolbar=no,location=no,directories=no,"+
  "status=no,menubar=no,scrollbars=no,"+
  "resizable=no,width="+width+",height="+height;
		  
  MyNewWindow=window.open(url,name,settings);
  MyNewWindow.focus();
}

// Simple browser window with only a scrollbar
function popup2(url, name, width, height) {
  settings=
  "toolbar=no,location=no,directories=no,"+
  "status=no,menubar=no,scrollbars=yes,"+
  "resizable=no,width="+width+",height="+height;
		  
  MyNewWindow=window.open(url,name,settings);
  MyNewWindow.focus();
 }


// same as above but with different settings
function popup3(url,name,ht,wd)
{
  settings=
  "toolbar=no,location=no,directories=no,"+
  "status=no,menubar=no,scrollbars=yes,"+
  "resizable=no,width="+wd+",height="+ht;
  pop = window.open(url,name,settings);
  pop.focus();
}

// fully customizable version
function popup4(url,name,settings)
{
  pop = window.open(url,name,settings);
  pop.focus();
}

// simple browser window without features and page position
function popup5(url, name, width, height, top, left) {
  settings=
  "toolbar=no,location=no,directories=no,"+
  "status=no,menubar=no,scrollbars=no,"+
  "resizable=no,width="+width+",height="+height+",top="+top+",left="+left;
		  
  var myname = name.replace(/ /g,'_');		// no spaces in window name!  
  MyNewWindow=window.open(url,myname,settings);
  MyNewWindow.focus();
}

// simple browser window with only a scrollbar and page position
function popup6(url, name, width, height, top, left) {
  settings=
  "toolbar=no,location=no,directories=no,"+
  "status=no,menubar=no,scrollbars=yes,"+
  "resizable=no,width="+width+",height="+height+",top="+top+",left="+left;
  var myname = name.replace(/ /g,'_');		// no spaces in window name!  
		  
  MyNewWindow=window.open(url,myname,settings);
  MyNewWindow.focus();
}



/* ********************* DONATIONS ** DONATIONS ***************** */
/* ********************* DONATIONS ** DONATIONS ***************** */
/* ********************* DONATIONS ** DONATIONS ***************** */

/*
 * The following are several functions used in the donation pages. 
 * They range from taking data out of the URL to display on page to
 * creating hyperlinks to giftany functions and comments for verisign.
 */

// This function lets us grab data out of the URL
function getUrlParm(url,parmname) { 
   qndx = url.indexOf("?"); 
   if(qndx < 0) return null; 
   parmndx = url.indexOf(parmname,qndx+1); 
   if(parmndx < 0) return null; 
   eqndx = url.indexOf("=",parmndx); 
   if(eqndx < 0) return null; 
   termndx = url.indexOf("&", eqndx); 
   if( termndx < 0 ) { 
     termndx = url.indexOf("#",eqndx); 
     if(termndx < 0) { 
       return unescape(url.substring(eqndx+1)); 
     } 
   } 
   return unescape(url.substring(eqndx + 1,termndx)); 
 } 

// This function makes the hyperlink to the gift any feature
function makehyperlink(lbl) {
    var url = window.location.href
    var projid = getUrlParm(url,"pid");
    var projpath = getUrlParm(url,"path");
    var projtitle = getUrlParm(url,"ptitle");
    var resturl = "/dy/gifts/gap.html?cmd=gifta&projid="+projid+"&projpath="+projpath+"&projtitle="+projtitle;
    document.write('<a href="'+resturl+'">'+lbl+'</a>')
}

// Test to make sure entered donation amount is valid
function is_a_num(number) {
    var tester = number * 1;
    // Check to make sure field is not blank
    if ((number == null) || (number.length == 0)){
	alert("Please enter a donation amount");
        return false;
    }
    // Check to make sure number is not negative or 0
    if (number < 1){
	alert("Please enter a positive donation amount");
        return false;
    }
    // Check to make sure number is indeed a number
    if (isNaN(tester) == true){
	alert("Please enter a valid donation amount");
        return false;
    }
    return true;
}

// Create comment field for verisign and submit verisign form
function descvalue() {
    var url = window.location.href
    // Gathering variables needed for comment field
    var projid = getUrlParm(url,"pid");
    var projtitle = getUrlParm(url,"ptitle");
    var donation = document.amt.AMOUNT.value;
    // Converting data from checkboxes into variables
    if(document.amt.ANON.checked){
       var anonymous = "a";
    } else {
      var anonymous = "p";
    }
    if(document.amt.NEWSL.checked){
      var newsletter = "r";
    } else {
      var newsletter = "u";
    }
    // Creating the verisign comment and description field
    document.amt.DESCRIPTION.value = (unescape(projtitle+" ("+projid+")"));
    document.amt.COMMENT1.value = ("d:-1:"+projid+":"+anonymous+":"+newsletter+":"+donation);
    // Submiting form if donation amount is a valid number
    if ( is_a_num(donation) == true ) {
       document.amt.submit();
    }
}

// copyright 1999 Idocs, Inc. http://www.idocs.com
// Distribute this script freely but keep this notice in place
function numbersOnly(myfield, e, dec)
{
var key;
var keychar;

if (window.event)
   key = window.event.keyCode;
else if (e)
   key = e.which;
else
   return true;
keychar = String.fromCharCode(key);

// control keys
if ((key==null) || (key==0) || (key==8) || 
    (key==9) || (key==13) || (key==27) )
   return true;

// numbers
else if ((("0123456789").indexOf(keychar) > -1))
   return true;

// decimal point jump
else if (dec && (keychar == "."))
   {
   myfield.form.elements[dec].focus();
   return false;
   }
else
   return false;
}



/* ********************* GIFTS GIFTS GIFTS ***************** */
/* ********************* GIFTS GIFTS GIFTS ***************** */
/* ********************* GIFTS GIFTS GIFTS ***************** */
/* ********************* GIFTS GIFTS GIFTS ***************** */

/*
 * The following functions let the user preview the information entered
 * for the gift cards.  there are two functions now as there are two cards
 */

// Gift Any Preview
function old_preview() {
  var projtitle = document.gift.projtitle.value;
  var projid = document.gift.projid.value;
  var projpath = document.gift.projpath.value;
  var recipient = document.gift.recip_fname.value;
  var message = document.gift.recip_msg.value;
  if (message.length > 200) {
     alert("The personalized message is above 200 characters, please reduce it.");
     var msgerror = "toolong";
  };
  var sender = document.gift.sender_fname.value;
  var sendlast = document.gift.sender_lname.value;		  
  if ((msgerror == null) || (msgerror.length == 0)) {
       popup("/cb/gap/gifts/giftprev.html?ptitle="+projtitle+"&pid="+projid+
	     "&path="+projpath+
             "&recname="+recipient+"&recmsg="+message+"&sender="+sender+
             "&lastname="+sendlast, 'Win1', 600, 430); return false;
  }
}

// Gift Package Preview
function preview2() {
  var message = document.gift.recip_msg.value;
  if (message.length > 200){
     alert("The personalized message is above 200 characters, please reduce it.");
     var msgerror = "toolong";
  };
  var sendfirst = document.gift.sender_fname.value;
  var sendlast = document.gift.sender_lname.value;
  var sender = sendfirst + " " + sendlast
  var pid = document.gift.projid.value;
  var path = document.gift.projpath.value;
  var text = document.gift.cardtext.value;
  cardtext = text.replace(/__/, sender);
  if ((msgerror == null) || (msgerror.length == 0)) {
       popup("/cb/gap/gifts/giftpkgprev.html?cardtext="+cardtext+"&pid="+pid+
	     "&path="+path+
             "&recmsg="+message+"&sender="+sendfirst+"&lastname="+sendlast, 
             'Win1', 600, 400); return false;
  };
}



/* ********************* URL MAKER ***************** */
/* ********************* URL MAKER ***************** */
/* ********************* URL MAKER ***************** */

/*  
 * Make the url to run htdig search on project partners for aboutds page
 */

function htdigurl(ngoname) {
document.write('<a href="/cgi-bin/htsearch?config=htdig&amp;restrict=&amp;exclude=&amp;method=and&amp;format=long&amp;sort=score&amp;words='+ngoname+'">View projects</a>')
    }

/*  
 * Make the url for the vote now button to link to the donate now page with
 * the project title and project id included in the url.
 */

function giveurl(pid,ptitle,path) {      
	///cb/gap/pr/2400/proj2376a.html
    // old document.write('<a href="/dy/gcart/gap.html?cmd=showgive&projid='+pid+'"><img alt="Give Now" border="0" src="/cb/gap/img/givenow.gif" style="margin-bottom:5px;"></a>')
    document.write('<a href="../'+path+'"><img alt="Give Now" border="0" src="/cb/gap/img/givenow.gif" style="margin-bottom:5px;"></a>');
}

function giveurl_form(pid,ptitle,path) {
    document.write('<input type="image" src="/cb/gap/img/givenow.gif" align="absbottom" border="0"')
}

function giveurl_formlg(pid,ptitle,path) {
    document.write('<input type="image" src="/cb/gap/img/givenow_lg.gif" style="margin-bottom: 11px;" border="0"')
}


/*  
 * Make the url for the vote now button to link to the donate now page with
 * the project title and project id included in the url.  This is for cobrands
 * Where the donate page is in the image directory
 */

function giveurl2(pid,ptitle) {
    document.write('<a href="/dy/gcart/gap.html?cmd=showgive&projid='+pid+'"><img alt="Give Now" border="0" src="/cb/gap/img/givenow.gif" style="margin-bottom:5px;"></a>')
}



/* ********************* COUNTRY INFO PAGES ***************** */
/* ********************* COUNTRY INFO PAGES ***************** */
/* ********************* COUNTRY INFO PAGES ***************** */

/*  
 * Makes sure graph bar width is always at least 1 on country stat pages
 */

function ctrywid(wid) {
    if ( wid < 2 ) {
	width = 2;
    }
	}

/*  
 * Navigate between various country info pages
 */

function gotoctry(page){
    selectedctry = document.ctry_nav.recip_ctryid.selectedIndex;
    ctryid = document.ctry_nav.recip_ctryid.options[selectedctry].value;
    ctryurl = '/ctry/ctryi' + page + ctryid + '.html'
    // alert("this is the url:   " + ctryurl)
    location.href = ctryurl;
}

/*  
 * Return to index or hall of fame index pages
 */

function indxlink(url){
    opener.location = url;
    window.close()
}


// CREATE A MAILTO URL OR MAILTO ANCHOR TAG
function createMailto(sourceForm, targetField, urlType) {
  var to      = sourceForm.to.value;
  var cc      = sourceForm.cc.value;
  var bcc     = sourceForm.bcc.value;
  var subject = sourceForm.subject.value;
  var body    = sourceForm.body.value;
  var linkText= sourceForm.linkText.value;
  
  if (linkText == "") {
    linkText = "Link Text";
  }
  
  var urltext = "";

  // IF THE VALUE IS SET, INCLUDE IT IN THE URL
  if (to != "") {
    urltext += to;
  }
  else {
    alert("Sorry, you must fill out the 'To' field");
    sourceForm.to.focus();
    return(1);
  }
  if (cc != "") {
    urltext = addDelimiter(urltext);
    urltext += "CC=" + cc;
  }
  if (bcc != "") {
    urltext = addDelimiter(urltext);
    urltext += "BCC=" + bcc;
  }
  if (subject != "") {
    urltext = addDelimiter(urltext);
    urltext += "Subject=" + escape(subject);
  }
  if (body != "") {
    urltext = addDelimiter(urltext);
    urltext += "Body=" + escape(body);
  }
  if (urlType == "url") {
    urltext = "mailto:" + urltext;
  }
  else {
    urltext = "<A HREF=\"mailto:" + urltext + "\">" + linkText + "</A>";
  }

  // PUT THE NEW URL IN THE FORM FIELD
  targetField.value = urltext;

  // GIVE THE FIELD FOCUS AND HIGHLIGHT THE TEXT -- 
  // TO FACILITATE EASY COPYING AND PASTING OF THE NEW URL
  targetField.focus();
  targetField.select();
  return(1);
}

// ADD THE "?" OR "&" NAME/VALUE SEPARATOR CHARACTER
function addDelimiter(inputString) {
  var inString = inputString;

  // IF '?' NOT FOUND, THEN THIS IS THE FIRST NAME/VALUE PAIR
  if (inString.indexOf("?") == -1) {
    inString += "?";
  }
  // ELSE IT'S A SUBSEQUENT NAME/VALUE PAIR, SO ADD THE '&' CHARACTER
  else {
    inString += "&";
  }
  return inString;
}

// TEST THE MAILTO URL -- ASSIGN THE URL TO THE DOCUMENT LOCATION
// TO POP UP THE MESSAGE WINDOW
function testMailto(loc) {
  var doc = loc;

  // IF MAILTO URL IS EMBEDDED IN AN ANCHOR TAG
  if (doc.indexOf("HREF=") != -1) {
    // EXTRACT THE MAILTO URL FROM THE ANCHOR TAG
    var doc = doc.substring(doc.indexOf("HREF=")+6, doc.indexOf(">")-1);
  }

  // ASSIGN THE MAILTO URL TO THE DOCUMENT (THIS WILL POP UP A MAIL WINDOW)
  window.location = doc;
}

function viewMailto(mailtoText) {
  alert("URL:\n\n" + mailtoText);
}



/* ********************* ROLLOVER MENU ***************** */
/* ********************* ROLLOVER MENU ***************** */
/* ********************* ROLLOVER MENU ***************** */

function startList() {

	// code for IE
	if(!document.body.currentStyle) return;
	var subs = document.getElementsByName('submenu');
	for(var i=0; i<subs.length; i++) {
		var li = subs[i].parentNode;
		if(li && li.lastChild.style) {
			li.onmouseover = function() {
				this.lastChild.style.visibility = 'visible';
			}
			li.onmouseout = function() {
				this.lastChild.style.visibility = 'hidden';
			}
		}
	}
}


/* ********************* INPUT LABELS ***************** */
/* ********************* INPUT LABELS ***************** */
/* ********************* INPUT LABELS ***************** */

function changeInputType(oldElm,iType,iValue,noFocus) {
  if(!oldElm || !oldElm.parentNode || (iType.length<4) ||
    !document.getElementById || !document.createElement) return;
  var newElm = document.createElement('input');
  newElm.type = iType;
  newElm.className = 'loginbox_input';
  if(oldElm.name) newElm.name = oldElm.name;
  if(oldElm.id) newElm.id = oldElm.id;
  newElm.onfocus = function() {
    if(this.hasFocus) return;
    var newElm = changeInputType(this,'password',
      (this.value.toLowerCase()=='password')?'':this.value);
    if(newElm) newElm.hasFocus=true;
  }
  newElm.onblur = function() {
    if(this.hasFocus)
    if(this.value=='' || this.value.toLowerCase()=='password') {
      changeInputType(this,'text','password',true);
    }
  }
 // hasFocus is to prevent a loop where onfocus is triggered over and over again
  newElm.hasFocus=false;
  oldElm.parentNode.replaceChild(newElm,oldElm);
  if(iValue) newElm.value = iValue;
  if(!noFocus || typeof(noFocus)=='undefined') {
    window.tempElm = newElm;
    setTimeout("tempElm.hasFocus=true;tempElm.focus();",1);
  }
  return newElm;
}

function maskPasswordInput() {
  var allowInputTypeChange = true;
  var fld1 = document.getElementById('login_passwd');
  if(document.getElementById) {
    try { // to keep IE from showing errors.
      fld1.type = 'text';
      if(fld1.type == 'text') fld1.value = 'password';
      else allowInputTypeChange = false;
    } catch(e) { allowInputTypeChange = false; }
  }
  if(allowInputTypeChange) {
    fld1.onfocus = function() {
      var tempVal = this.value; // NS6 fix.
      var iType = this.type; // Opera 7 fix.
      if(this.type != 'password') this.type = 'password';
      this.value = tempVal; // NS6 fix.
      if(this.value.toLowerCase()=='password')
        this.value = '';
      if(window.opera && iType != 'password') this.focus();
    }
    fld1.onblur = function() {
      if(this.type == 'password')
      if(this.value=='' || this.value.toLowerCase()=='password') {
        this.type = 'text';
        this.value = 'password';
      }
    }
  }

  // need to detect Konqueror and Safari which don't have unique objects,
  // will use the user agent string to detect them. Only use this type of
  // detection as a last resort.  doing this because crashes Konqueror 
  // and Safari and generates errors in IE5/Mac

  var ua = navigator.userAgent.toLowerCase();
  if(!((ua.indexOf('konqueror')!=-1) && (document.all || 
    (ua.indexOf('khtml/3.4')!=-1))) && !(((ua.indexOf('safari')!=-1) && 
    !window.print) || (document.defaultCharset && !window.print)))
      changeInputType(document.getElementById('login_passwd'),'text','password',true);
}

function clearLoginInput(thefield) {
    if (thefield.name=="email") {
        if (thefield.defaultValue==thefield.value)
	thefield.value = ""
    }
}

function checkLoginInput(thefield) {
    if (thefield.name=="email" && thefield.value=="") {
        thefield.value = "email address"
    }
}

/** ******************************** */
/*
 * Client-side access to querystring name=value pairs
 * http://adamv.com/dev/javascript/querystring Version 1.2.3 22 Jun 2005 Adam
 * Vandenberg
 */
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = new Object()
	this.get = Querystring_get

	if (qs == null)
		qs = location.search.substring(1, location.search.length)

	if (qs.length == 0)
		return

		// Turn <plus> back to <space>
		// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
		qs = qs.replace(/\+/g, ' ')
	var args = qs.split('&') // parse out name/value pairs separated via &

	// split out each name=value pair
	for ( var i = 0; i < args.length; i++) {
		var value;
		var pair = args[i].split('=')
		var name = unescape(pair[0])

		if (pair.length == 2)
			value = unescape(pair[1])
		else
			value = name

		this.params[name] = value
	}
}

function Querystring_get(key, default_) {
	// This silly looking line changes UNDEFINED to NULL
	if (default_ == null)
		default_ = null;

	var value = this.params[key]
	if (value == null)
		value = default_;

	return value
}

// copyright 1999 Idocs, Inc. http://www.idocs.com
// Distribute this script freely but keep this notice in place
function currencyOnly(myfield, e, dec) {
	var key;
	var keychar;

	if (window.event) {
		key = window.event.keyCode;
	} else if (e) {
		key = e.which;
	} else {
		return true;
	}

	keychar = String.fromCharCode(key);

	// control keys
	if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13)
			|| (key == 27)) {
		return true;
	}
	// numbers
	else if ((("0123456789").indexOf(keychar) > -1)) {
		return true;
	} else {
		// allow one decimal point
		if ("." == keychar || "," == keychar) {
			return true;
		} else {
			return false;
		}
	}
}

/**
 * this function will print (called from receipt.wm) the receipt but hide the
 * survey fields first, then re-show them.
 */
function printReceipt() {
	var surv = document.getElementById('rcpt_survey');
	if (surv != null) {
		surv.style.cssText = "display:none"; // hide the survey
		window.print();
		surv.style.cssText = "disiplay:block"; // un-hide the survey
	} else {
		window.print();
	}
}

function validateNumber(pComponent, showAlert, pLabel, pWhole, pPrecision, pMin, pMax)
{
   pComponent.value = removeAllSpaces(pComponent.value);
   
   var amount = removeAllCommas(pComponent.value);
   var msg;
   var reFloat;
   var valFloat = parseFloat(amount);
   if (isNaN(valFloat))	// first validate entered value is a number
   {
   		if (showAlert)
   		{
   			alert(pLabel + " is required to be a number between " + pMin + " and " + pMax + ".");
      		pComponent.select();
      		setTimeout(function(){pComponent.focus()},10);
      	}
      return false;
   }
   if (pWhole)			// whole number (integer)
   {
   		msg = pLabel + " must be an Integer between " + pMin + " and " + pMax + ".";
   		// this regexp allows optional ".00" after the number
   		reFloat = /^-?[\d,]*\.?0{0,2}$/;
   	}
   	else		// decimal number with pPrecision decimal places
   	{
   		msg = pLabel + " must be a decimal number with " + pPrecision + " decimal places between " + pMin + " and " + pMax + ".";
      reFloat = new RegExp("^-?[\\d,]*\\.?\\d{0,"+pPrecision+"}$");
   }
   if (!(reFloat.test(amount)))
   {
		if (showAlert)
		{
			alert(msg);
			pComponent.select();
			setTimeout(function(){pComponent.focus()}, 10);
		}
		return false;
	}
	if (valFloat < pMin || valFloat > pMax)  // validate between min and max
	{
		if (showAlert)   
		{
			alert(msg);
			pComponent.select();
			setTimeout(function(){pComponent.focus()}, 10);
		}
		return false;
	}
	return true;
}
function trim(pString)
{  
   return pString.replace(/^\s+/g, '').replace(/\s+$/g,'');
}
function removeAllSpaces(pString)
{  
   return pString.replace(/\s+/g, '');
}
function removeAllCommas(pString)
{  
   return pString.replace(/,+/g, '');
}