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

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

function allLinksNonSSL(document)
{
  for (var i=0;i<document.links.length;i++)
  {
  	if (document.links[i].protocol == 'https:')
  	{
  	  document.links[i].protocol = 'http:';
  	  document.links[i].port = 80;	// required for IE browsers
  	}
  }
}
/*
 * This is the main onload function that will call others
 */

function pageOnLoad() {
//   alert('The cobrand is :'+getCobrandFromURL());
   grabRefCode();
//   startMenu();
   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();
     }
   }
   // if this is tne "new" cart receipt page, and we are using ssl, then change all 
   // links on the page to return to non-ssl mode.
   if (location.pathname.indexOf('/cart/receipt/') > -1 && location.protocol == 'https:')
   {
      allLinksNonSSL(document);
   }
}



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

function startMenu() {

  // code for IE rollovers
  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';
      }
    }
  }
  var subs = document.getElementsByName('submenu_topic');
  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';
      }
    }
  }
  var subs = document.getElementsByName('submenu_region');
  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';
      }
    }
  }
}

function expandMenuItem(strElementID) {
  var menu_selection = (strElementID);
  var selection = document.getElementById(menu_selection);

  //if choose by topic selected
  if (menu_selection == "topic1") {
    if (selection.style.display == "block") {

    var elements = document.getElementsByName('submenu_topic');
    if (elements != null) {
      for(var i = 0; i < elements.length; i++) {
      elements[i].style.cssText = "display: none;";
      }
    }
    var elements = document.getElementsByName('submenu_region');
    if (elements != null) {
      for(var i = 0; i < elements.length; i++) {
      elements[i].style.cssText = "display: none;";
      }
    }

    } else {

    var elements = document.getElementsByName('submenu_topic');
    if (elements != null) {
      for(var i = 0; i < elements.length; i++) {
      elements[i].style.cssText = "display: block;";
      }
    }
    var elements = document.getElementsByName('submenu_region');
    if (elements != null) {
      for(var i = 0; i < elements.length; i++) {
      elements[i].style.cssText = "display: none;";
      }
    }

    }
  }

  //if choose by region selected
  if (menu_selection == "region1") {
    if (selection.style.display == "block") {

    var elements = document.getElementsByName('submenu_region');
    if (elements != null) {
      for(var i = 0; i < elements.length; i++) {
      elements[i].style.cssText = "display: none;";
      }
    }
    var elements = document.getElementsByName('submenu_topic');
    if (elements != null) {
      for(var i = 0; i < elements.length; i++) {
      elements[i].style.cssText = "display: none;";
      }
    }

    } else {

    var elements = document.getElementsByName('submenu_region');
    if (elements != null) {
      for(var i = 0; i < elements.length; i++) {
      elements[i].style.cssText = "display: block;";
      }
    }
    var elements = document.getElementsByName('submenu_topic');
      if (elements != null) {
        for(var i = 0; i < elements.length; i++) {
        elements[i].style.cssText = "display: none;";
        }
      }

      }
    }

}


/* ********************* CATALOG PAGE ** CATALOG PAGE ***************** */

function toggleItem(strElementID) {
  if (document.getElementById("panel" + strElementID).style.display == "none") { 
      expandItem(strElementID);
  } else { 
      collapseItem(strElementID);
  }
}

function expandItem(strElementID) {
    document.getElementById("panel" + strElementID).style.display = "block"; 
    document.getElementById("image" + strElementID).src = "/img/icons/collapse.gif"; 
}
function collapseItem(strElementID) {
     document.getElementById("panel" + strElementID).style.display = "none";
     document.getElementById("image" + strElementID).src = "/img/icons/expand.gif"; 
}


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

/*
 * Note: as of 4/18/06 - additional functionality added to the onload to:
 * Parse the query string of the URL looking for 'rf=xxxx'
 * If found, a ggRefCode Cookie is created (or overwritten) with the
 * contents being xxxx.  The cookie will expire in 30 days.
 * This is to facilitate identifying donations as from a certain source.
 * The referring URL (from a google adword, or referral from another site)
 * Must contain the query string "?rf=xxxx", to be recognized.
 * The giving cart will add this refcode to each giving cart item in the
 * promotion code.
 *
 * Note: as of 4/25/06 - this used to be in a forcewww() onload script
 * don't need this anymore, can be handled by apache.  so took out url
 * ref code checking and put in own function.
 */

function grabRefCode() {

   // Check for a referral code in the query string...
   // parse the query string on this page, and see if it has an rf=*
   // if so, put the * in cookie called ggRefCode
   var query = location.search.substring(1);
   var pairs = query.split("&");  //split pairs by ampersand
   for (var i = 0;i< pairs.length;i++) 
   {
       var pos = pairs[i].indexOf("=");
       if (pos == -1) continue; 
       var argname = pairs[i].substring(0,pos).toLowerCase();
       if (argname.toLowerCase() == "rf") 
       {
          var value = pairs[i].substring(pos+1);
          setCookie("ggRefCode", value, 30, "/");
       }
   }
}

/**
 * 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:inline"; // un-hide the survey
  }
  else
  {
    window.print();
  }
}

/**
 * this function will print (called from receipt.wm) the receipt
 * but hide the survey fields first, then re-show them.
 */
function printreceiptBlock()
{
  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 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/vfpserv.html?cmd=login&andthen=/');

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

    var test = document.cookie.indexOf('ggUserName=')
    if (test > -1) 
    {
        var begin = document.cookie.indexOf('ggUserName=')+11;
	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 '
			+ href_logout
                        + ' >Welcome&nbsp;' + scv 
                        + '&nbsp;-&nbsp;Logout</a>');
    }
    else {
	    document.write('<a '
                           + href_login
                           + ' >Welcome&nbsp;Guest&nbsp;-&nbsp;Login</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/vfpserv.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';
  popup2(url,name,width,height);
}

/**
 * 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 = 'gg';
   var path = location.pathname;
   // first check for alternative hostnames....
   if (location.hostname.indexOf("globalgrandparenting") > -1) return result; // same as gg
   else if (location.hostname.indexOf("americagives") > -1) return 'ag';
   else if (location.hostname.indexOf("givingchallenge") > -1) return 'ag';
   if (path==null || path.length < 3)
   {
      if (location.hostname.indexOf("globalgiving") > -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 = 'gg';
		}
		else if (path.indexOf("/dy/") > -1)
      {
         // find the html portion
         var re = /(\/.*)+\/(.+)\.html/;
         var matches = path.match(re);
         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 == 'cidi') result = 'gg'; // cidi and gg are the same!!
      return result;
   }
}



/* ********************* 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 = CookieString.substring(offset,end);
//      alert('[getCookieValue]encoded="'+result+'",unencoded="'+decodeURIComponent(result)+'"');               
      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 )
}

/** 
 * Get a cookie value ONLY for specified path
 */
function getCookieValue(Name, Path)
{
 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 = unescape(CookieString.substring(offset, end))         
//      result = CookieString.substring(offset,end);
//      alert('[getCookieValue]encoded="'+result+'",unencoded="'+decodeURIComponent(result)+'"');               
      result = decodeURIComponent(CookieString.substring(offset, end))         
                                                
      } 
    }
   return result;                                
}
/**
 * Remove a cookie.
 */
function deleteCookie(Name, Path) {
  setCookie(Name,"Deleted", -1, Path)
}



/* ********************* 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("?");
  var qstring=true;

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

  // Then find the querystring, everything after the ?
  if (qstring == true) {
  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) {
//document.value_outcomes.vo[3].checked=true;
form.amount.focus();
}

function clearTextBox(form) {
if (form && form.amount) {
form.amount.value='';
}
}
function validateOtherAmt(f)
{
  if (f.vo_id.value == -1)  // validate amount?
  {
    var x=f.amount.value
    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 and less than US $10,000.");
      f.amount.value='';
      setTimeout(function(){f.amount.focus()},10);
      f.amount.focus();
      return false;
    }
    if (x >= 10 && x <= 10000) {
      //alert("pass test >= 10");
    } else {
      //alert("fail test >= 10");
      alert("Donation amount must be a whole number greater than US $10 and less than US $10,000.");
      setTimeout(function(){f.amount.focus()},10);
      f.amount.focus();
      return false;
    }
  }
  return true;
}



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

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

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

function mkaddr5(addr,subj,body,label) {
  document.write('<a class="menutab" href=\"mailto:' + addr
	+ '?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 mkaddr3(addr,label,font) {
  site = "globalgiving.com";
  document.write('<a class=\"' + font + '\" href=\"mailto:' + addr + '@' + site 
        + '\">' + label + '</a>');
}

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

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

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

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

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

function emailafriend(body,url,lbl) {
    document.write('<a href="mailto:?body=' + escape(body) + 'Check it out at http://www.globalgiving.com/'+url+'">'+lbl+'</a>');
}

function tellafriend(body,lbl) {
    document.write('<a href="mailto:?body=' + escape(body) + 'Check it out and consider making a donation at http://www.globalgiving.com/' + '\">'+lbl+'</a>');
}

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

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



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

/*
 * Functions that call up a pop-up window.  Settings vary for new window.
 * all force focus back to the popup
 */


// 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;
  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
function popup2(url, name, width, height) {
  var settings=
  "scrollbars,width="+width+",height="+height;
  var myname = name.replace(/ /g,'_');		// no spaces in window name!  
  MyNewWindow=window.open(url,myname,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;
  var myname = name.replace(/ /g,'_');		// no spaces in window name!  
  pop = window.open(url,myname,settings);
  pop.focus();
}

// fully customizable version
function popup4(url,name,settings)
{
  var myname = name.replace(/ /g,'_');		// no spaces in window name!  
  pop = window.open(url,myname,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 ***************** */

/*
 * 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/vfpserv.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();
    }
}
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, '');
}

/*
 * This function takes several parameters and a DOM element to validate its value 
 * is a number.  It will validate decimal numbers with specified precision, or]
 * whole numbers with an optional trailing ".00" to handle currency.
 * The parameters:
 * pComponent - reference to the HTML Dom element to be validated
 * showAlert - pass in true or false to tell function whether it should 
 *             set focus on pComponent and display a javascript alert if no pass.
 * pLabel - the string to prepend to the error message (usually the descriptive field label).
 * pWhole - boolean (true or false) if the number to be validated is integer only
 * pPrecision - applies only if pWhole is false, the number if decimal places (maximum) allowed.
 * pMin - the minimum value allowed for this field
 * pMax - the maximum value allowed for this field
 */
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;
}

// 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 ***************** */

/*
 * 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("/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("/gifts/giftpkgprev.html?cardtext="+cardtext+"&pid="+pid+
	     "&path="+path+
             "&recmsg="+message+"&sender="+sendfirst+"&lastname="+sendlast, 
             'Win1', 600, 400); return false;
  };
}



/* ********************* 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 give 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) {
    document.write('<a href="/dy/gcart/vfpserv.html?cmd=showgive&projid='+pid+'"><img alt="Give Now" src="/img/buttons/give_now.gif" align="absbottom" border="0"></a>')
	}

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

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

function giveurl_refcode(pid,ptitle,path,refcode) {
     document.write('<a href="/dy/gcart/vfpserv.html?cmd=showgive&projid='+pid+'&RF='+refcode+'"><img alt="Give Now" src="/img/buttons/give_now.gif" border="0"></a>')
        }

/*  
 * Make the url for the give 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/vfpserv.html?cmd=showgive&projid='+pid+'"><img alt="Give Now" border="0" src="/img/buttons/give_now.gif"></a>')
	}



/* ********************* 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);
}



/* ********************* PARTNER LOGO SLIDE SHOW ON HOMEPAGE ***************** */


/***********************************************
* Ultimate Fade-In Slideshow (v1.5): © Dynamic Drive (http://www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for this script and 100s more.
***********************************************/
 
var fadeimages=new Array()
//SET IMAGE PATHS. Extend or contract array as needed. Corporate and Institutional Partners 0-19, Funding Partners 20-25
fadeimages[0]=["/aboutus/img/amd.gif", "/aboutus/partners.html#2"]
fadeimages[1]=["/aboutus/img/aol.gif", "/aboutus/partners.html#3"]
fadeimages[2]=["/aboutus/img/amatlogo.gif", "/aboutus/partners.html#4"]
fadeimages[3]=["/aboutus/img/create_hope.gif", "/aboutus/partners.html#5"]
fadeimages[4]=["/aboutus/img/cidilogo.gif", "/aboutus/partners.html#6"]
fadeimages[5]=["/aboutus/img/denali.gif", "/aboutus/partners.html#7"]
fadeimages[6]=["/aboutus/img/dai.gif", "/aboutus/partners.html#8"]
fadeimages[7]=["/aboutus/img/ebay.gif", "/aboutus/partners.html#9"]
fadeimages[8]=["/aboutus/img/gap_logo.gif", "/aboutus/partners.html#gap"]
fadeimages[9]=["/aboutus/img/google_logo.gif", "/aboutus/partners.html#google"]
fadeimages[10]=["/aboutus/img/hp.gif", "/aboutus/partners.html#10"]
fadeimages[11]=["/aboutus/img/jkgroup.gif", "/aboutus/partners.html#11"]
fadeimages[12]=["/aboutus/img/newheroes_logo.gif", "/aboutus/partners.html#newheroes"]
fadeimages[13]=["/aboutus/img/tnf.gif", "/aboutus/partners.html#13"]
fadeimages[14]=["/aboutus/img/ovt_logo.gif", "/aboutus/partners.html#ovt"]
fadeimages[15]=["/aboutus/img/participant_logo.gif", "/aboutus/partners.html#participant"]
fadeimages[16]=["/aboutus/img/paypal_logo.gif", "/aboutus/partners.html#paypal"]
fadeimages[17]=["/aboutus/img/sistercities.gif", "/aboutus/partners.html#sistercities"]
fadeimages[18]=["/aboutus/img/visa.gif", "/aboutus/partners.html#14"]
fadeimages[19]=["/aboutus/img/yahoo.gif", "/aboutus/partners.html#15"]
fadeimages[20]=["/aboutus/img/mott.gif", "/aboutus/partners.html#55"]
fadeimages[21]=["/aboutus/img/omidyar_logo.gif", "/aboutus/partners.html#omidyar"]
fadeimages[22]=["/aboutus/img/skoll.gif", "/aboutus/partners.html#50"]
fadeimages[23]=["/aboutus/img/usaid_gda.gif", "/aboutus/partners.html#51"]
fadeimages[24]=["/aboutus/img/hewlett.gif", "/aboutus/partners.html#52"]
fadeimages[25]=["/aboutus/img/wkkf.gif", "/aboutus/partners.html#54"]
fadeimages[26]=["/aboutus/img/leoburnett.gif", "/aboutus/partners.html#leoburnett"]

var fadebgcolor="white"
 
//NO need to edit beyond here//
 
var fadearray=new Array() //array to cache fadeshow instances
var fadeclear=new Array() //array to cache corresponding clearinterval pointers
 
var dom=(document.getElementById) //modern dom browsers
var iebrowser=document.all
 
function fadeshow(theimages, fadewidth, fadeheight, borderwidth, delay, pause, displayorder){
this.pausecheck=pause
this.mouseovercheck=0
this.delay=delay
this.degree=10 //initial opacity degree (10%)
this.curimageindex=0
this.nextimageindex=1
fadearray[fadearray.length]=this
this.slideshowid=fadearray.length-1
this.canvasbase="canvas"+this.slideshowid
this.curcanvas=this.canvasbase+"_0"
if (typeof displayorder!="undefined")
theimages.sort(function() {return 0.5 - Math.random();}) //thanks to Mike (aka Mwinter) :)
this.theimages=theimages
this.imageborder=parseInt(borderwidth)
this.postimages=new Array() //preload images
for (p=0;p<theimages.length;p++){
this.postimages[p]=new Image()
this.postimages[p].src=theimages[p][0]
}
 
var fadewidth=fadewidth+this.imageborder*2
var fadeheight=fadeheight+this.imageborder*2
 
if (iebrowser&&dom||dom) //if IE5+ or modern browsers (ie: Firefox)
document.write('<div id="master'+this.slideshowid+'" style="position:relative;width:'+fadewidth+'px;height:'+fadeheight+'px;overflow:hidden;"><div id="'+this.canvasbase+'_0" style="position:absolute;width:'+fadewidth+'px;height:'+fadeheight+'px;top:0;left:0;filter:progid:DXImageTransform.Microsoft.alpha(opacity=10);-moz-opacity:10;-khtml-opacity:10;background-color:'+fadebgcolor+'"></div><div id="'+this.canvasbase+'_1" style="position:absolute;width:'+fadewidth+'px;height:'+fadeheight+'px;top:0;left:0;filter:progid:DXImageTransform.Microsoft.alpha(opacity=10);-moz-opacity:10;background-color:'+fadebgcolor+'"></div></div>')
else
document.write('<div><img name="defaultslide'+this.slideshowid+'" src="'+this.postimages[0].src+'"></div>')
 
if (iebrowser&&dom||dom) //if IE5+ or modern browsers such as Firefox
this.startit()
else{
this.curimageindex++
setInterval("fadearray["+this.slideshowid+"].rotateimage()", this.delay)
}
}

function fadepic(obj){
if (obj.degree<100){
obj.degree+=10
if (obj.tempobj.filters&&obj.tempobj.filters[0]){
if (typeof obj.tempobj.filters[0].opacity=="number") //if IE6+
obj.tempobj.filters[0].opacity=obj.degree
else //else if IE5.5-
obj.tempobj.style.filter="alpha(opacity="+obj.degree+")"
}
else if (obj.tempobj.style.MozOpacity)
obj.tempobj.style.MozOpacity=obj.degree/101
else if (obj.tempobj.style.KhtmlOpacity)
obj.tempobj.style.KhtmlOpacity=obj.degree/100
}
else{
clearInterval(fadeclear[obj.slideshowid])
obj.nextcanvas=(obj.curcanvas==obj.canvasbase+"_0")? obj.canvasbase+"_0" : obj.canvasbase+"_1"
obj.tempobj=iebrowser? iebrowser[obj.nextcanvas] : document.getElementById(obj.nextcanvas)
obj.populateslide(obj.tempobj, obj.nextimageindex)
obj.nextimageindex=(obj.nextimageindex<obj.postimages.length-1)? obj.nextimageindex+1 : 0
setTimeout("fadearray["+obj.slideshowid+"].rotateimage()", obj.delay)
}
}
 
fadeshow.prototype.populateslide=function(picobj, picindex){
var slideHTML=""
if (this.theimages[picindex][1]!="") //if associated link exists for image
slideHTML='<a href="'+this.theimages[picindex][1]+'" target="'+this.theimages[picindex][2]+'">'
slideHTML+='<img src="'+this.postimages[picindex].src+'" border="'+this.imageborder+'px">'
if (this.theimages[picindex][1]!="") //if associated link exists for image
slideHTML+='</a>'
picobj.innerHTML=slideHTML
}
 
 
fadeshow.prototype.rotateimage=function(){
if (this.pausecheck==1) //if pause onMouseover enabled, cache object
var cacheobj=this
if (this.mouseovercheck==1)
setTimeout(function(){cacheobj.rotateimage()}, 100)
else if (iebrowser&&dom||dom){
this.resetit()
var crossobj=this.tempobj=iebrowser? iebrowser[this.curcanvas] : document.getElementById(this.curcanvas)
crossobj.style.zIndex++
fadeclear[this.slideshowid]=setInterval("fadepic(fadearray["+this.slideshowid+"])",50)
this.curcanvas=(this.curcanvas==this.canvasbase+"_0")? this.canvasbase+"_1" : this.canvasbase+"_0"
}
else{
var ns4imgobj=document.images['defaultslide'+this.slideshowid]
ns4imgobj.src=this.postimages[this.curimageindex].src
}
this.curimageindex=(this.curimageindex<this.postimages.length-1)? this.curimageindex+1 : 0
}
 
fadeshow.prototype.resetit=function(){
this.degree=10
var crossobj=iebrowser? iebrowser[this.curcanvas] : document.getElementById(this.curcanvas)
if (crossobj.filters&&crossobj.filters[0]){
if (typeof crossobj.filters[0].opacity=="number") //if IE6+
crossobj.filters(0).opacity=this.degree
else //else if IE5.5-
crossobj.style.filter="alpha(opacity="+this.degree+")"
}
else if (crossobj.style.MozOpacity)
crossobj.style.MozOpacity=this.degree/101
else if (crossobj.style.KhtmlOpacity)
crossobj.style.KhtmlOpacity=obj.degree/100
}
 
 
fadeshow.prototype.startit=function(){
var crossobj=iebrowser? iebrowser[this.curcanvas] : document.getElementById(this.curcanvas)
this.populateslide(crossobj, this.curimageindex)
if (this.pausecheck==1){ //IF SLIDESHOW SHOULD PAUSE ONMOUSEOVER
var cacheobj=this
var crossobjcontainer=iebrowser? iebrowser["master"+this.slideshowid] : document.getElementById("master"+this.slideshowid)
crossobjcontainer.onmouseover=function(){cacheobj.mouseovercheck=1}
crossobjcontainer.onmouseout=function(){cacheobj.mouseovercheck=0}
}
this.rotateimage()
}



/* ********************* VALIDATION FOR RECEIPT FEEDBACK SURVEY ***************** */

/**
* Sets the Maxlength for the Text Area, 
 * use by calling this in the textarea's onkeyup and onkeydown.
 */
function textCounter(field,maxlimit,displayid,prefix) 
{
   if (field.value.length > maxlimit)
   {
      field.value = field.value.substring(0, maxlimit);
   }
   if (displayid != null)
   {
	  var count = maxlimit - field.value.length;
	  if (prefix != null)
	  {
   	  	document.getElementById(displayid).innerHTML = prefix + count + '&nbsp;characters remaining';
   	  }
   	  else
   	  {
   	  	document.getElementById(displayid).innerHTML = '(' + count + '&nbsp;characters remaining)';
   	  }
   }  
}


function checkboxReceiptValidate()
{
// set var checkbox_choice to false
var checkbox_choice1 = false;
var checkbox_choice2 = false;
var checkbox_choice3 = false;
var checkbox_choice4 = false;
var checkbox_choice5 = false;
var checkbox_choice6 = false;
var comments_choice7 = false;
// Check if any of the values are true
   if (document.formRecptSurvey.a1.checked) {
       checkbox_choice1 = true; }
   if (document.formRecptSurvey.a2.checked) {
       checkbox_choice2 = true; }
   if (document.formRecptSurvey.a3.checked) {
       checkbox_choice3 = true; }
   if (document.formRecptSurvey.a4.checked) {
       checkbox_choice4 = true; }
   if (document.formRecptSurvey.a5.checked) {
       checkbox_choice5 = true; }
   if (document.formRecptSurvey.a6.checked) {
       checkbox_choice6 = true; }
   if (document.formRecptSurvey.a7.value.length > 0) {
       comments_choice7 = true; }

   if (!checkbox_choice1 && !checkbox_choice2 && !checkbox_choice3 && 
       !checkbox_choice4 && !checkbox_choice5 && !checkbox_choice6
    && !comments_choice7)
   {
      alert("Please select at least one answer and/or\nprovide comments to submit your response.")
         return (false);
   }
   return (true);
}


/* ********************* OPEN VOTE DATE DRAWDOWN ***************** */

/* 	Realtime Countdown v1.1
 *	(C) 2006 Nathan Bolender
 *	www.nathanbolender.com
*/

/*	**********************************************************	*/
/*	**********************************************************	*/
/*	**************** DO NOT EDIT BELOW THIS LINE**************	*/
/*	**********************************************************	*/
/*	**********************************************************	*/

var version = '1.1';
		
function countdown(elementString, dateString, mode, name) { 

// date in format "December 25, 2005 00:00:00 GMT-500"
//
//	usage:
//	countdown(str element, str date [, int mode [, str name]])
//	element is the element that will contain the countdown
//	date is the countdown (or countup) date in this standard form:
//		December 25, 2005 00:00:00 GMT-500
//
//	Modes:
//	0 (default): Time until My Birthday - 06:33:00 11/25/05: 6 hours, 28 minutes, and 36 seconds.
//	1: My Birthday - 06:33:00 11/25/05: 6 hours, 28 minutes, and 36 seconds.
//	2: 6 hours, 28 minutes, and 36 seconds.
//	3: 6 hours, 28 minutes, and 36 seconds

if (mode == null) mode = 0;
if (name == null) name = '0';
	var clock = document.getElementById(elementString);
	var eventdate = new Date(dateString); // in format "January 1, 2005 00:00:00 GMT"
	now = new Date();
	nowtime = now.getTime(); // now in milliseconds
	eventtime = eventdate.getTime(); // event in milliseconds
		
		var eventhour = eventdate.getHours();
		var eventminute = eventdate.getMinutes();
		var eventsecond = eventdate.getSeconds();
		var eventmonth = eventdate.getMonth()+1;
		var eventday = eventdate.getDate();
		var eventyear = eventdate.getFullYear();

	timeleft = Math.round((eventtime-nowtime) / 1000); // timeleft in seconds
	
	var passed = 0;
	if (timeleft < 0) { // if event has passed
		timeleft = Math.abs(timeleft);
		passed = 1;
	}
	
	if (timeleft != 0) {
		// Let's get a whole bunch of values
		years = Math.floor(timeleft/31556926);
		months = Math.floor((timeleft%31556926)/2629744);
		days = Math.floor(((timeleft%31556926)%2629744)/86400);
		hours = Math.floor((((timeleft%31556926)%2629744)%86400)/3600);
		minutes = Math.floor(((((timeleft%31556926)%2629744)%86400)%3600)/60);
		seconds = Math.floor(((((timeleft%31556926)%2629744)%86400)%3600)%60);
	}
	
	// Now lets build a response to print
	var togo = ''; // set up our variable
	
	if (mode == 0) {
		togo += 'only ';
		if (passed != 1) {
			togo += 'until ';
		} else {
			togo += 'since ';
		}
	}
	
	if ((mode != 2) && (mode != 3)) {
		togo += '<strong>';
		if (name != '0') togo += name + ' - ';
		if ((eventhour + eventminute + eventsecond) != 0) {
			togo += eventhour + ':' + eventminute;
			if (eventsecond != 0) togo += ':' + eventsecond;
			togo += ' on ';
		}
		togo += eventmonth + '/' + eventday;
		if (eventyear != now.getFullYear()) togo += '/' + eventyear;
		togo += '</strong>: ';
	}
	
	if (timeleft != 0) {
	   togo = '<a href="/cb/open/" style="font-family: Arial; font-size: 13px;">Vote now</a> &mdash; only&nbsp;';
		if (years > 0) {
			togo += years + ' year';
			if (years > 1) togo += 's';
			if (months > 0) togo += ', ';
			if ((minutes!=0)||(seconds!=0)||(hours!=0)||(days!=0)||(months!=0)) togo += ' ';
		}
		
		if (months > 0) {
			togo += months + ' month';
			if (months > 1) togo += 's';
			if (days > 0) togo += ', ';
			if ((minutes!=0)||(seconds!=0)||(hours!=0)||(days!=0)) togo += ' ';
		}
		
		if (days >= 0) {
			togo += days + ' day';
			if (days > 1) togo += 's';
			if (hours >= 0) togo += ', ';
			if ((minutes!=0)||(seconds!=0)||(hours!=0)) togo += ' ';
		}
		
		if (hours >= 0) {
			togo += hours + ' hour';
			if (hours > 1) togo += 's';
			if (minutes >= 0) togo += ', ';
			if ((minutes!=0)||(seconds!=0)) togo += ' ';
		}
		
		if (minutes >= 0) {
			togo += minutes + ' minute';
			if (minutes > 1) togo += 's';
			if (seconds >= 0) togo += ', ';
			if (seconds!=0) togo += ' ';
		}

		if (seconds >= 10) {
			togo += seconds + ' seconds left to go!';
		}

		if (seconds < 10) {
			togo += '0' + seconds + ' second';
			if (seconds > 1) togo += 's';
			if (seconds >= 0) togo += ' left to go!';
		}
		
		var expld = togo.split(', ');
		// EXAMPLE:
		// 0 => 5 years
		// 1 => 5 months
		// 2 => 5 days
		// 3 => 5 hours
		// 4 => 5 minutes
		// 5 => 5 seconds
		
		var exlast = expld.length-1;
		var todo = '';
		var i;
		
		for (i=0 ; i<expld.length ; i++) {
			value = expld[i];
			todo += value;
			if ((i != exlast) && (expld.length!=2)) todo += ', ';
			if ((expld.length == 2) && (i != exlast)) todo += ' ';
			if (i == (exlast-1)) todo += 'and ';
			if ((i == exlast) && (passed == 1)) todo = 'Voting has closed.';
			if ((i == exlast) && (mode != 3)) todo += '.';
		}
	} else {
		var todo = togo + 'Voting Finished!';
	}
	
	// Now lets print it
	if (clock != null) clock.innerHTML = todo;
	
	setTimeout('countdown(\'' + elementString + '\', \'' + dateString + '\', ' + mode + ', "' + name + '");', 1000); // re-execute the function in 1 second
}

/***********************************/
/* 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
}


var BrowserDetect = {
   init: function () {
      this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
      this.version = this.searchVersion(navigator.userAgent)
         || this.searchVersion(navigator.appVersion)
         || "an unknown version";
      this.OS = this.searchString(this.dataOS) || "an unknown OS";
   },
   searchString: function (data) {
      for (var i=0;i<data.length;i++)  {
         var dataString = data[i].string;
         var dataProp = data[i].prop;
         this.versionSearchString = data[i].versionSearch || data[i].identity;
         if (dataString) {
            if (dataString.indexOf(data[i].subString) != -1)
               return data[i].identity;
         }
         else if (dataProp)
            return data[i].identity;
      }
   },
   searchVersion: function (dataString) {
      var index = dataString.indexOf(this.versionSearchString);
      if (index == -1) return;
      return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
   },
   dataBrowser: [
      {  string: navigator.userAgent,
         subString: "OmniWeb",
         versionSearch: "OmniWeb/",
         identity: "OmniWeb"
      },
      {
         string: navigator.vendor,
         subString: "Apple",
         identity: "Safari"
      },
      {
         prop: window.opera,
         identity: "Opera"
      },
      {
         string: navigator.vendor,
         subString: "iCab",
         identity: "iCab"
      },
      {
         string: navigator.vendor,
         subString: "KDE",
         identity: "Konqueror"
      },
      {
         string: navigator.userAgent,
         subString: "Firefox",
         identity: "Firefox"
      },
      {
         string: navigator.vendor,
         subString: "Camino",
         identity: "Camino"
      },
      {     // for newer Netscapes (6+)
         string: navigator.userAgent,
         subString: "Netscape",
         identity: "Netscape"
      },
      {
         string: navigator.userAgent,
         subString: "MSIE",
         identity: "Explorer",
         versionSearch: "MSIE"
      },
      {
         string: navigator.userAgent,
         subString: "Gecko",
         identity: "Mozilla",
         versionSearch: "rv"
      },
      {     // for older Netscapes (4-)
         string: navigator.userAgent,
         subString: "Mozilla",
         identity: "Netscape",
         versionSearch: "Mozilla"
      }
   ],
   dataOS : [
      {
         string: navigator.platform,
         subString: "Win",
         identity: "Windows"
      },
      {
         string: navigator.platform,
         subString: "Mac",
         identity: "Mac"
      },
      {
         string: navigator.platform,
         subString: "Linux",
         identity: "Linux"
      }
   ]

};
BrowserDetect.init();