/********************************************************************************
*      Script: common.js
* Description: Several common routines 
*    Comments: intellectual property of Clint Collier: on loan to iyfr.
*     Created: 01/23/2005 [CLC]
*    Modified: 07/15/2006 [CLC] added assistant webmaster to mailing list as 8 
*					bumping all others down a number
*    Modified  08/29/2006 [JNB] changed email rotarymariners to iyfr
*    Modified  11/10/2006 [CLC] routines to edit input form fields    
*	  Modified  1 July 2007 [JNB] 19 pastcommodore to past_commodore             
*	  Modified  1 July 2007 [JNB] 14 changed rotafloat Publisher to events secretary 
*    Modified  1 July 2007 [JNB] changed cc of emails 
*	  Modified 2007/08/21 [clc] Update of documentation for FixMail
*********************************************************************************/

                                    
//***************************************************************************
// Reverse a string; abcd become dcba
//***************************************************************************
function reverse_string() {
   if (this.length <= 1) return this;
	var reversestring = "";
   for (var x = 0; x < this.length; x++) {
      reversestring = this.charAt(x) + reversestring;
   }
   return reversestring;
} //reverse_string
String.prototype.reverse = reverse_string



//***************************************************************************
// 2007/08/21 [clc] Update documentation to show subject is required.
//	This function derives the correct e-mail for an e-mail link when the user 
// clicks on the link to send.  The 'onclick' option of each of these links 
// passes the real name and system address written in reverse which tells us 
// which real address to send the message to.  the calling code for this is... 
// <A href="mailto:iyfrinfo@iyfr.net" 
//			onclick="FixMail(this,'reversename','reverseatvalue','Subject:');"> 
//***************************************************************************
function FixMail(email, faketoname, fakeatname, subject) {  
	var oldemail;
	var realtoname;
	var realatname;
	oldemail = email.href;
// reverse the order to give us our real value here.
	realtoname = faketoname.reverse();
	realatname = fakeatname.reverse();
	var atsign = "@";
// Set the correct hyperlink e-mail address
	if (subject.length >= 0) {
	   email.href = "mailto:" + realtoname + atsign + realatname + '?Subject=' + subject; }
	else {
		email.href = "mailto:" + realtoname + atsign + realatname; }
	/*
	for debuging....
	alert("Fake E-mail address was ... \n   " + oldemail + "\n\n\n" +
			"Real E-mail address is  ... \n   " + email.href);
	*/
	return true;             // make it work...
} //FixMail


//***************************************************************************
// Send mail to various bridge officers.
// This function derives the correct e-mail for an e-mail link when the user 
// clicks on the link to send.  All e-mails in the system are set to 
// iyfrinfo@iyfr.net which is a spam trap for harvesting bots and which 
// gets forwarded to my private id for messages sent to such harvested addresses.
// The 'onclick' option of each of these links passes a number which tells us 
// which real address to send the message to.
// the calling code for this is 
// <A href="mailto:iyfrinfo@iyfr.net" onclick="IYFRMail(this,nn);"> 
// where nn is the number [base 0] of the true e-mail address; 
// see the following email_name array.
//***************************************************************************
function IYFRMail(email, emailindex, subject) {  
	var oldemail;
	oldemail = email.href;
	var atsign = "@";
	var where = "iyfr.net";
	var atwhere = atsign + where;
	/* legitimate addresses on this site...
		 0 = info (defaults to chief of staff; cc to administrator)
		 1 = commodore
		 2 = vicecommodore
		 3 = rearcommodore
		 4 = chief of staff
		 5 = administrator
		 6 = secretary
		 7 = webmaster
		 8 = asst webmaster
		 9 = auditor (cc to administrator)
		10 = treasurer (cc to administrator)
		11 = regalia (cc to assistant treasurer; cc to administrator)
		12 = public relations
		13 = rotafloat (cc to commodore)
		14 = events secretary
		15 = legal
		16 = area1 commodore
		17 = area2 commodore
		18 = area3 commodore
		19 = past commodore
	*/
	var email_name = new Array("info", "commodore", "vicecommodore", "rearcommodore", "chiefofstaff", "administration", "secretary", "webmaster", "asstwebmaster","auditor", "treasurer", "regalia", "publicrelations", "rotafloat", "events", "legal", "area1commo", "area2commo", "area3commo", "past_commodore");
	
	if (parseInt(emailindex) > 19 || parseInt(emailindex) < 0) {
		/* for debugging...
		alert("Fake E-mail address was ... \n   " + oldemail + "\n\n\n" +
		      "Real E-mail address is  ... \n   " + email.href + "\n\n\n" +
				"Failed indes is: " + emailindex + " " + parseInt(emailindex));
		*/
		email.href = oldemail
	}
	else {
		// Set the correct hyperlink e-mail address
		email.href = "mailto:" + email_name[emailindex] + atwhere;
		if (subject == " ") {
			subject = "Rotary IYFR: Question from web site- ";
		}
		// Append the subject
		email.href = email.href + "?subject=" + subject;
		// Set any copies we want to send...
		switch(emailindex) {
			case '0':
				email.href = email.href + "&cc" + email_name[4] + atwhere;
				break;
			case '13':
				email.href = email.href + "&cc" + email_name[1] + atwhere;
				break;
			default :
				email.href = email.href;
		} //switch
/*
case '9' :
				email.href = email.href + "&cc=" + email_name[5] + atwhere; 
				break;
			case '10' :
				email.href = email.href + "&cc=" + email_name[5] + atwhere; 
				break;
			case '11' :
				email.href = email.href + "&cc=" + email_name[5] + atwhere + "," + email_name[9] + atwhere;
				break;
*/
		
	if (subject == "Interest in joining IYFR") {
		email.href = email.href + 
			"&body=Please include your full name, mailing address, name of your Rotary club, and phone number in this e-mail.";
	}
	} //if in range
	/* for debuging.... 
		alert("Fake E-mail address was ... \n   " + oldemail + "\n\n\n" +
		      "Real E-mail address is  ... \n   " + email.href)
	*/
	return true;  // make it work...
} //IYFRMail


//***************************************************************************
// Open a window of a specified size
// Similar to function openPopub but disallows box to be resizable
//***************************************************************************
function open_window(name,url,h,w) {
	Version=navigator.appVersion;
	var showpic=null
	var chrome = "scrollbars"
	
	w=w+20;
	if (is_IE()) {
		h=h+80
	}
	else {
		h=h+30
	}
	chrome = chrome+",width="+w+",height="+h
	showpic = window.open(url,name,chrome)
	if ((Version.substring(0,1)>= 3) && (Version.indexOf("MSIE") == -1)) {
		showpic.focus();
	}
} //open_window


//***************************************************************************
// Open a popup box of a specified size
// Similar to function open_window but allows box to be resizable
//***************************************************************************
function openPopup(name,url,w,h) {
	Version=navigator.appVersion;
	var showpic=null
	var chrome = "scrollbars,resizable"
	
	w=w+20;
	if (is_IE()) {
		h=h+80
	}
	else {
		h=h+30
	}
	chrome = chrome+",width="+w+",height="+h
	showpic = window.open(url,name,chrome)
	if ((Version.substring(0,1)>= 3) && (Version.indexOf("MSIE") == -1)) {
		showpic.focus();
	}
} //openPopup


//***************************************************************************
// Determine if the browser is Microsoft (requires popup box to be longer)
//***************************************************************************
function is_IE() {
	var user_agent = navigator.userAgent.toLowerCase()
	return (user_agent.indexOf("msie") != -1) 
} // is_IE

//***************************************************************************
// Refresh a form
//***************************************************************************
function Refresh(list_name,current_form,returntopgm) {		
	if (list_name == "area") {
		var user_selection = current_form["area_id_list"].options[current_form["area_id_list"].selectedIndex].value			
		current_form.action=returntopgm + "?selected_area_id=" + user_selection
	}
	if (list_name == "region") {
		var user_selection = current_form["region_id_list"].options[current_form["region_id_list"].selectedIndex].value			
		current_form.action=returntopgm + "?selected_region_id=" + user_selection
	}
	if (list_name == "fleet") {
		var user_selection = current_form["fleet_id_list"].options[current_form["fleet_id_list"].selectedIndex].value
		current_form.action=returntopgm + "?selected_fleet_id=" + user_selection
	}
	current_form.submit()
} // Refresh

//***************************************************************************
// Refresh a form scheduled to be REMOVED
//***************************************************************************
function oldRefresh(list_name,current_form,returntopgm) {	
	if (list_name == "area") {
		var user_selection = current_form[0].options[current_form[0].selectedIndex].value			
		current_form.action=returntopgm + "?selected_area_id=" + user_selection
	}
	if (list_name == "region") {
		var user_selection = current_form[1].options[current_form[1].selectedIndex].value			
		current_form.action=returntopgm + "?selected_region_id=" + user_selection
	}
	if (list_name == "fleet") {
		var user_selection = current_form[2].options[current_form[2].selectedIndex].value
		current_form.action=returntopgm + "?selected_fleet_id=" + user_selection
	}
	current_form.submit()
} // Refresh



//***************************************************************************
// Check to see if a user marked member records for deletion.
// If he did, ask if he is sure he wants to delete them
//***************************************************************************
function ConfirmDelete(member_form) {
	// Because the names of our check boxes are set up for handling in php in the
	// format delete[], i.e. a php array, we can not access them directly in javascript
	// which rejects the name because of the [] embeded in it.  Therefore, to check
	// the fields in javascript we must access them through their array position.
	// Thus, we step throut the entire list of form elements looking for checkboxes,
	// when we find one we check to see if it is true or false, and if true, count it!'
	with (member_form) {
		var recordstodelete = 0
		for (var counter = 0; counter < elements.length; counter++) {
			if (elements[counter].type == 'checkbox') {
				if (elements[counter].checked) {
					recordstodelete++
				}
			}
		}
	} // with (member_form)
	// check to see if any of the boxes are checked...
	if (recordstodelete >= 1) {
		if (recordstodelete >= 2) {
			var records = 'these ' + recordstodelete + ' records?'
		}
		else {
			var records = ' this record?'
		}
		if (confirm('Are you sure you want to delete ' + records)) {
			return true
		}
		else {
			with (member_form) {
				for (var counter = 0; counter < elements.length; counter++) {
					if (elements[counter].type == 'checkbox') {
						elements[counter].checked = false
					}
				}
			} // with (member_form)
			alert ('Delete cancelled!')
			return false
		}			
	}
	else {
		// User did not mark any records to delete?
		alert('You have not marked any recrods to delete!')
		return false
	}
} // ConfirmDelete


//***************************************************************************
// Refresh to calling window from a popup and close the popup
//***************************************************************************
function refreshParent() {
  window.opener.location.href = window.opener.location.href;
  if (window.opener.progressWindow) {
    window.opener.progressWindow.close();
  }
  window.close();  
} // refreshParent


//***************************************************************************
// 							MEMBER INPUT SCREEN EDITS
//
//***************************************************************************
// Put an error message on the input screen or clear it
//***************************************************************************
function DisplayError(errormessage) {
	document.getElementById('errormessage').innerHTML = errormessage;
} // Display Error
//----------------------------
function ClearError() {
	document.getElementById('errormessage').innerHTML = "<BR />";
} // ClearError


//***************************************************************************
// Validate the email_field 
//		The clear field is used when the function is called from the screen
//		to clear the error field if no error.  When calling this routine from
//		the ValidateMemberForm we want to leave any errors we have shown.
//***************************************************************************
function ValidateEMail(email_field,clear) {
	if (email_field.value == "-none-") return true;
	// this regular expression pattern taken from 
	//		http://www.regular-expressions.info/email.html
	//var pattern = /^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/;
	
	// this regular expression pattern taken from 
	// "The Java Scrip Anthology" Edwards & Adams, pg 61.
	// Note the need of "our" /... / opening and closing delimiters.
	var pattern = /^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$/; 	
	if (!(pattern.test(email_field.value))) {
		DisplayError("The eMail Address in not valid!");
		email_field.focus
		return false;
	}
	if (clear) ClearError();
	return true;
} // ValidateEMail


//***************************************************************************
// Validate the text_field 
//		The clear field is used when the function is called from the screen
//		to clear the error field if no error.  When calling this routine from
//		the ValidateMemberForm we want to leave any errors we have shown.
//***************************************************************************
function ValidateTextField(display_fieldname,field,clear) {
	var pattern = /^\s+$/;
	if (field.value == "" || pattern.test(field.value)) {
		DisplayError(display_fieldname+" can not be left blank!");
		field.focus
		return false;
	} 
	if (clear) ClearError();
	return true;
} //ValidateTextField


//***************************************************************************
// Validate the form
//		This function is set to be called by an ...onsubmit statement located
//		in the calendar.js routine (all forms use the calendar)
//***************************************************************************
function ValidateMemberDetail(){
	var return_cd = true;
	var elements = document.forms["member_detail"].elements;
	ClearError();
	for (var x = 0; x < elements.length; x++) {
		elementclass = elements[x].className;
		if (elementclass.substr(0,13) == "checkrequired") {
			checktoperform = elementclass.substr(14);
			if (checktoperform == "e-mail") {
				if (!ValidateEMail(elements[x])) return_cd = false;
			} else {
				if(!ValidateTextField(checktoperform,elements[x],false)) return_cd = false;
			}
		}
	} // for
	return return_cd;
} // ValidateMemberDetail
