
function emailCheck (fieldname,blankOK,emailStr) {

var emailPat=/^(.+)@(.+)$/;
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
var validChars="\[^\\s" + specialChars + "\]";
var quotedUser="(\"[^\"]*\")";
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
var atom=validChars + '+';
var word="(" + atom + "|" + quotedUser + ")";
var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

if(emailStr=="") {
	if (blankOK==true) {
		return true;
	} else {
		alert(fieldname + " cannot be blank");
		return false;
	}
}
	emailStr = emailStr.replace(/\s/g,"");
var matchArray=emailStr.match(emailPat);
if (matchArray==null) {
	alert(fieldname + ": Seems incorrect (check @ and .'s)")
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid 
if (user.match(userPat)==null) {
    // user is not valid
    alert(fieldname + ": The username doesn't seem to be valid.")
    return false
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        alert(fieldname + ":Destination IP address is invalid!")
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert(fieldname + ":The domain name doesn't seem to be valid.")
    return false
}

/* domain name seems valid, but now make sure that it ends in a
   two or more letter domain or country (allowing for new >3 domains), and that there's a hostname preceding 
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 ) {
   // the address must end in a two or more letter domain name .
   alert(fieldname + ":The address must end in a two or more letter domain (e.g., com, edu, org).")
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr=": This address is missing a hostname!"
   alert(fieldname + errStr)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}

function notBlank(fieldname,value){

if (value == "") {
	alert(fieldname + " can't be blank");
	return false;
}
return true;
}
function notNull(fieldname,value){

if (value == null) {
	alert(fieldname + ": a value must be selected");
	return false;
}
return true;
}

function notUnchecked(fieldname,rad) {

for (i=0;i< rad.length;i++) {
	if (rad[i].checked) {
		return true;
	}
}
alert(fieldname + ": one option must be checked");
return false;
}

function validateNumericField_notBlank(fieldname,field,length) {
var valid = "0123456789";


if (field.length!=length) {
alert(fieldname + " must be " + length + " digits long");
return false;
}
for (var i=0; i < field.length; i++) {
temp = "" + field.substring(i, i+1);
if (valid.indexOf(temp) == "-1") {
alert(fieldname + ": Only numbers are allowed  Please try again.");
return false;
}
}
return true;
}

function validateNumericField_BlankOK(fieldname,field,length) {
var valid = "0123456789";

if (field.length == 0) {
	return true;
}

if (field.length!=length) {
alert(fieldname + " must be " + length + " digits long or blank.");
return false;
}
for (var i=0; i < field.length; i++) {
temp = "" + field.substring(i, i+1);
if (valid.indexOf(temp) == "-1") {
alert(fieldname + ": Only numbers are allowed  Please try again.");
return false;
}
}
return true;
}

function validateNumeric_BlankOK(fieldname,field) {
var valid = "0123456789";

if (field.length == 0) {
	return true;
}

for (var i=0; i < field.length; i++) {
temp = "" + field.substring(i, i+1);
if (valid.indexOf(temp) == "-1") {
alert(fieldname + ": Only numbers are allowed  Please try again.");
return false;
}
}
return true;
}




function validateOnePhoneOrEmailNonBlank(phone1,phone2,email1)
{

if (phone1 == "" && phone2 == "" && email1 == "") {
	alert(" You must supply either a phone number or an email address");
	return false;
}

return true;
}

function validatePhoneOrEmailNonBlank(phone,email)
{

if (phone == ""  && email == "") {
	alert(" You must supply either a phone number or an email address");
	return false;
}

return true;
}

function atLeastOneCheckboxChecked(groupDescription, theform){
	toSubmit = false;
	var arr = new Array();
	for ( var i = 0 ; i < theform.elements.length; i++ ){
	  var elm = theform.elements[i];
	  if ( elm.type == "checkbox" ){
		arr[arr.length] = elm;
	  }
	}
	 
	for( var i = 0; i < arr.length; i++){
	 var checkbox = arr[i];
	 if (checkbox.checked ) {
		toSubmit = true;
		break;
	 }
	}
	if(!toSubmit) alert("At least one " + groupDescription + " must be checked.");
	return toSubmit;
}

function QueryString(key)
{
    var value = null;
    for (var i=0;i<QueryString.keys.length;i++)
    {
        if (QueryString.keys[i]==key)
        {
            value = QueryString.values[i];
            break;
        }
    }
    return value;
}
QueryString.keys = new Array();
QueryString.values = new Array();

function QueryString_Parse()
{
    var query = window.location.search.substring(1);
    var pairs = query.split("&");
    
    for (var i=0;i<pairs.length;i++)
    {
        var pos = pairs[i].indexOf('=');
        if (pos >= 0)
        {
            var argname = pairs[i].substring(0,pos);
            var value = pairs[i].substring(pos+1);
            QueryString.keys[QueryString.keys.length] = argname;
            QueryString.values[QueryString.values.length] = value;      
        }
    }

}

QueryString_Parse();

function setLev(){
	nodeid = 0;

	lnstr = document.getElementById("contentleft").innerHTML.toLowerCase();
	nstrt = lnstr.indexOf('class="nav1" href="/page.do?n=');
	if(nstrt == -1) nstrt = lnstr.indexOf('class=nav1 href="/page.do?n=');
	if(nstrt > -1){
                nstrt = lnstr.indexOf('?n=',nstrt);
		nend = lnstr.indexOf('"',nstrt);
		if(nend > nstrt) nodeid = lnstr.substring(nstrt+3,nend);

	} 

	if(nodeid == "2"){
		document.images['about'].src = "/images/nav_about_over.gif";
	}
	if(nodeid == "3"){
		document.images['ourpriorities'].src = "/images/nav_ourpriorities2_over.gif";
	}
	if(nodeid == "4"){
		document.images['cando'].src = "/images/nav_cando_over.gif";
	}
	if(nodeid == "5"){
		document.images['news'].src = "/images/nav_news_over.gif";
	}
	
	// Spanish
	if(nodeid == "1057"){
		document.images['sobreai'].src = "/images/nav_sobreai2_over.gif";
	}
	if(nodeid == "1075"){
		document.images['temas'].src = "/images/nav_temas2_over.gif";
	}
	if(nodeid == "1065"){
		document.images['colabora'].src = "/images/nav_colabora2_over.gif";
	}
	if(nodeid == "1276"){
		document.images['noticias'].src = "/images/nav_noticias2_over.gif";
	}
	// Members section should not be live
	if(nodeid == "13"){
		document.location.href="/members/index.html";
	}	
	return false;
}



function social_networking(whch){
	t=document.title;
	t=encodeURIComponent(t);
	u=location.href;
	u=encodeURIComponent(u);
	switch(whch){
		case 1:
		str = "http://del.icio.us/post?v=4&noui&jump=close&url=" + u + "&title=" + t;
		break;
		case 2:
		str = "http://digg.com/submit?phase=2&url=" + u + "&title=" + t;
		break;
		case 3:
		str = "http://www.facebook.com/share.php?u=" + u + "&t=" + t;
		break;
		case 4:
		str = "http://ma.gnolia.com/bookmarklet/add? url=" + u + "&title=" + t;
		break;
		case 5:
		str = "http://www.newsvine.com/_tools/seed&save?u=" + u + "&h=" + t;
		break;
		case 6:
		str = "http://reddit.com/submit?url=" + u + "&title=" + t;
		break;
		case 7:
		str = "http://www.spurl.net/spurl.php?url=" + u + "&title=" + t;
		break;
		default:
		return false;
		break;
	}
	window.open(str,'socnet',',resizable=1,scrollbars=1,status=1,width=670,height=500').focus();
	return false;
}

// Example: nospam2("domain,"info","com");
function nospam2(domain,name,tld){
	document.write('<a href=\"mail' + 'to:' + name + '@' + domain + '.' + tld + '\">');
	document.write(name + '@' + domain + '.' + tld + '</a>');
}

function trimAll(sString) 
{
	while (sString.substring(0,1) == ' ')
	{
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

function Cookie_Get( check_name ) {
 // first we'll split this cookie up into name/value pairs
 // note: document.cookie only returns name=value, not the other components
 var a_all_cookies = document.cookie.split( ';' );
 var a_temp_cookie = '';
 var cookie_name = '';
 var cookie_value = '';
 var b_cookie_found = false; // set boolean t/f default f
 
 for ( i = 0; i < a_all_cookies.length; i++ )
 {
  // now we'll split apart each name=value pair
  a_temp_cookie = a_all_cookies[i].split( '=' );
  
  
  // and trim left/right whitespace while we're at it
  cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
 
  // if the extracted name matches passed check_name
  if ( cookie_name == check_name )
  {
   b_cookie_found = true;
   // we need to handle case where cookie has no value but exists (no = sign, that is):
   if ( a_temp_cookie.length > 1 )
   {
    cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
   }
   // note that in cases where cookie is initialized but no value, null is returned
   return cookie_value;
   break;
  }
  a_temp_cookie = null;
  cookie_name = '';
 }
 if ( !b_cookie_found )
 {
  return null;
 }
}

function Cookie_Set( name, value, expires, path, domain, secure ) 
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

function last3Links(){
	var linkcount = 0;
	var plinks = new Array();
	var ptitles = new Array();
	
	for(q=1;q<4;q++){
		plinks[q] = Cookie_Get("link" + q);
		ptitles[q] = Cookie_Get("title" + q);
//		alert("q=" + q + " link="+plinks[q] + " title=" + ptitles[q]);
		if(plinks[q] == null || ptitles[q] == null || typeof(plinks[q]) == "undefined" || typeof(ptitles[q]) == "undefined") break;
		else linkcount++;
	}
	
	// Remove duplicates
	if(linkcount == 2 && (plinks[1] == plinks[2] || plinks[1] == document.location.href)){
		plinks[1] = plinks[2];
		plinks[2] = null;
		linkcount = linkcount - 1; 
	}
	if(linkcount == 3 && plinks[1] == plinks[3]){
		plinks[1] = plinks[2];
		plinks[2] = plinks[3];
		plinks[3] = null;
		linkcount = linkcount - 1; 
	}
	if(linkcount == 3 && (plinks[2] == plinks[3] || plinks[2] == document.location.href)){
		plinks[2] = plinks[3];
		plinks[3] = null;
		linkcount = linkcount - 1; 
	}
	
	
	// If count == 3 Rewrite links, make link 3 link 2, make link2 link 1, add current unless same as last
	if(!(document.location.href == plinks[3])){
		if(linkcount == 3){
			Cookie_Set("link1",plinks[2],4,'/','amnestyusa.org','');
			Cookie_Set("title1",ptitles[2],4,'/','amnestyusa.org','');
			Cookie_Set("link2",plinks[3],4,'/','amnestyusa.org','');
			Cookie_Set("title2",ptitles[3],4,'/','amnestyusa.org','');
			Cookie_Set("link3",document.location.href,4,'/','amnestyusa.org','');
			Cookie_Set("title3",document.title,4,'/','amnestyusa.org','');
		} else {
			Cookie_Set("link" + (linkcount+1),document.location.href,4,'/','amnestyusa.org','');
			Cookie_Set("title" + (linkcount+1),document.title,4,'/','amnestyusa.org','');
		}
	} else {
		linkcount = linkcount - 1;	
	}
	//alert(linkcount + " l type" + typeof(plinks[q]));
	// If count > 1 write Most recent pages visited on our site
	if(linkcount > 1){
		writeLinks(plinks,ptitles,linkcount);
	}

}

function writeLinks(l,t,c){
	str = "<p><b>Recently visited pages</b><br />";
		
	for(i=c;i>0;i--){
		// Make sure there are no tags
		if(t[i].indexOf(">") > -1) continue;
		if(t[i].indexOf("<") > -1) continue;
		if(l[i].indexOf(">") > -1) continue;
		if(l[i].indexOf("<") > -1) continue;
		
		// Make sure it's a reasonable length
		tl = t[i].length;
		if(t[i].length < 1) continue;
		t[i] = t[i].substring(0,65);
		if(tl > 65) t[i] = t[i] + "...";

		ll = l[i].length;
		l[i] = l[i].substring(0,255);
		if(ll > 255) continue;

		// Make sure it's an amnesty link
		validlink = false;
		if(l[i].toLowerCase().indexOf("http://www.aiusa.org") == 0) validlink = true;
        if(l[i].toLowerCase().indexOf("http://www.amnestyusa.org") == 0) validlink = true;
		if(l[i].toLowerCase().indexOf("http://amnestyusa.org") == 0) validlink = true;
		if(l[i].toLowerCase().indexOf("http://takeaction.amnestyusa.org") == 0) validlink = true;
		if(!(document.location.href == l[i]) && validlink) str += '<a href="'+ l[i] + '">' + t[i] + '</a><br />';
	}
	
	str += "</p>";
	linklist = document.getElementById("listlinks");
	if(linklist){
		linklist.innerHTML = str;
		if(str.length>50) linklist.style.display = "";
	}
}

function expandPriorities(){
 	var maxpriorityitems = 5;
 	pbexp = document.getElementById("expand");
	
	if(pbexp && pbexp.innerHTML == "Expand [+]"){
		pbexp.innerHTML = "Collapse [&ndash;]";
		for(itmct = 2; itmct < maxpriorityitems; itmct++){
			pbitem = document.getElementById("row" + itmct);
			if(pbitem) pbitem.style.display = "";
		}
		frames['RPCFrame'].location.href="/Issues/expandercount.php";
	} else {
		pbexp.innerHTML = "Expand [+]";
		for(itmct = 2; itmct < maxpriorityitems; itmct++){
			pbitem = document.getElementById("row" + itmct);
			if(pbitem) pbitem.style.display = "none";
		}
	}
}