String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}

String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

var imagesMap = new Array();

function animate(imageId, imagePaths, pauseLength) {
	var images = new Array();
	for (var i = 0; i < imagePaths.length; i++) {
		images[i] = new Image();
		images[i].src = imagePaths[i];
	}
	imagesMap[imageId] = images;
	animateLoop(imageId, pauseLength, 0);
}

function animateLoop(imageId, pauseLength, frame) {
	var images = imageMap[imageId];
	document.getElementById(imageId).src = images[frame].src;
	frame = (frame + 1) % images.length;
	timeout_state = setTimeout("animateLoop('" + imageId + "', " + pauseLength + ", " + frame + ")", pauseLength);
}

//jump to the location given.  This will redirect the current window to the new location
function jumpToLocation(location) {
   if (location.length == 0) {
     alert("Please select a value from the list.");
     return;
   }
   document.location.href = location;
}
  
var windowMap = new Array();

function popupWindow(url, targetId, width, height, toolbar, scrollbars, location, statusbar, menubar, resizable) {
	var oldWindow = windowMap[targetId];
	if ((oldWindow != null) && (window != oldWindow)) {
		oldwindow.close();
	}
	if (targetId == null) {
		targetId = 'default_' + (new Date()).getTime();
	}
	if (width == null) {
		width = window.width;
	}
	if (height == null) {
		height = window.height;
	}
	if (toolbar == null) {
		toolbar = 0;
	} 
	if (scrollbars == null) {
		scrollbars = 0;
	}
	if (location == null) {
		location = 0;
	}
	if (statusbar == null) {
		statusbar = 0;
	}
	if (menubar == null) {
		menubar = 0;
	}
	if (resizable == null) {
		resizable = 0;
	}
	windowMap[targetId] = window.open(
		url, 
		targetId, 
		'toolbar=' + toolbar + ',' +
			'scrollbars=' + scrollbars + ',' +
			'location=' + location + ',' +
			'statusbar=' + statusbar + ',' +
			'menubar=' + menubar + ',' +
			'resizable=' + resizable + ',' +
			'width=' + width + ',' +
			'height=' + height
	);
}

//function IsAuthorwareControl()
//   on error resume next
//   MM_AWARE = False
//   MM_AWARE = IsObject(CreateObject("Macromedia.AuthorwareShockwaveControl.1"))
//   IsAuthorwareControl = MM_AWARE
// End Function

function checkForAuthorware() {
	var MM_AWARE = false;
	for (i = 0; i < navigator.plugins.length; i++) {
		if (navigator.plugins[i].name.indexOf("Authorware") != -1) {
			MM_AWARE = parseFloat(navigator.plugins[i].description.substring(navigator.plugins[i].description.indexOf("version ") + 8)) >= 7.0;
		}
	}
	if (!MM_AWARE && window.ActiveXObject) {
		try {
			var authObj = new ActiveXObject("Macromedia.AuthorwareShockwaveControl.1");
			MM_AWARE = true;
		} catch (e) {
			MM_AWARE = false;
		}
	}
	if (MM_AWARE) {
		document.write('The Authorware 7.0 Web Player is installed on your computer. You may select ');
		document.write('the Run Authorware Demo button to start the demo.');
	} else {
		document.write('The Authorware 7.0 Web Player is not installed on your computer.<br /><br />');
		document.write('Select the Download Authorware Player button ');
		document.write('below to download the player from the Macromedia Web site.<br /><br />');
		document.write('<a href="javascript:downloadAuthorwarePlayer();" class="authorwaredownload"><span>Download Player</span></a> <br /><br />');
		document.write('<em>Note: Downloading this software may take up to 16 minutes ');
		document.write('using a 28.8 modem and requires 3.2 MB of hard drive space. ');
		document.write('AOL users should read the Tips below.</em><br /><br />');
		document.write('When the Authorware player has been installed, ');
		document.write('select the Run Authorware Demo button to view the demo.<br /><br /> ');
		document.write('');
		document.write('');
	}
}

function downloadAuthorwarePlayer() {
	// get the browser platform
	var platform;
	if (navigator.appVersion.indexOf("Win") != -1) {
		platform = "Windows";
	} else if(navigator.appVersion.indexOf("Mac") != -1) {
		platform = "Macintosh";
	} else {
		platform ="Other";
	}
	
	var ns4 = document.layers;
	var ns6 = document.getElementById && !document.all;
	var ie4 = document.all;
	var location;

	if (platform == "Windows") {
		if (ns4 || ns6) {
			location = 'http://www.macromedia.com/shockwave/download/download.cgi?P1_Prod_Version=AWPcmpl70&P2_Platform=Win32&P3_Browser_Version=NetscapePre4&P5_Language=English';
		} else if (ie4) {
			location = 'http://www.macromedia.com/shockwave/download/download.cgi?P1_Prod_Version=AWPcmpl70&P2_Platform=Win32&P3_Browser_Version=MSIE&P5_Language=English';
		}
	} else if (platform == "Macintosh") { // NOTE: assuming Mac OS X
		location = 'http://www.macromedia.com/shockwave/download/download.cgi?P1_Prod_Version=AWPcmpl&P2_Platform=MacOSX&P3_Browser_Version=NetscapePre4&P5_Language=English';
	} else {
		location = 'http://www.macromedia.com/shockwave/download/alternates/index.html';
	}

	window.open(location,'','resizable=yes,scrollbars=yes,toolbar=yes,menubar=yes,address=yes,status=yes,width=800,height=600');
}

function validateForm(myForm) {
	var requiredFields = myForm.RequiredFields.value.split(',');
	var requiredDesc = myForm.RequiredDesc.value.split(',');
	
	var errors = "";
	for (var i = 0; i < requiredFields.length; ++i) {
		var field = eval('myForm.' + requiredFields[i]);
		if (field.value.trim().length == 0) {
			if (errors.length == 0) {
				field.focus();
			}
			errors += 'Please provide a value for ' + requiredDesc[i] + '\n';
		}
	}
	
	var emailString = (myForm.EmailAddress) ? myForm.EmailAddress.value.trim() : null;
	if (emailString.length > 0) {
		if (validEmail(emailString)) {
			// The email is OK.
		} else {
			if (errors.length == 0) {
				myForm.EmailAddress.focus();
			}
			errors += 'Incorrect email address format.\n	Must be following format: name@domain.ext\n	For example: fred@aol.com\n';
		}
	}
	
	if (errors.length == 0) {
		return true;
	} else {
		alert('Please fix the following errors:\n\n' + errors);
		return false;
	}
}

function validEmail(emailString) {
	if (emailString.trim().length > 0) {
		if (emailString.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) {
			// The email is OK.
			return true;
		} else {
			return false;
		}
	}
}

function containsAccentCharacters(s) {
	for (i = 0; i < s.length; i++) {
		if (s.charCodeAt(i) > 127) {
			return true;
		}
	}
	
	return false;
}

function isOutLyingDomestic(country) {
	if (
		(country == "Virgin Islands, US")
		|| (country == "VI")
		|| (country == "US")
		|| (country == "AS")
		|| (country == "DC")
		|| (country == "FM")
		|| (country == "GU")
		|| (country == "MH")
		|| (country == "MP")
		|| (country == "PW")
		|| (country == "PR")
	) {
		return true;
	}

    return false;
}

function isDomesticUS(country) {
	if (
		(country == "United States")
		|| (country == "US")
		|| (country == "United States - Outlying Islands")
		|| ( isOutLyingDomestic( country ) )
	) {
		return true;
	}
	
	return false;
}

function isNumeric(inputString) {
	var numbers = "0123456789";
	var s = inputString.trim();
	var c = "";
	for (i = 0; i < s.length; i++) {
		c = s.charAt( i );
		if (numbers.indexOf(c) == -1) {
			return false;
		}
	}
	return true;
}

function validatePrayerRequest(form) {
	var maxlimit = 1000
	try {
		form.remLen.value = maxlimit - form.PrayerRequest.value.length;
		if (form.remLen.value < 0) {
			alert(
				"Due to system requirements, prayer requests can be no more than " + maxlimit + " characters\n" +
				"\n" +
				"We apologize for any inconvenience."
			);
			return false;
		}

		// first, validate the form contents
		var country = form.Country.value;
		var firstName = form.FirstName.value;
		var lastName = form.LastName.value;
		var address = form.Address1.value;
		var address2 = form.Address2.value;
		var address3 = form.Address3.value;
		var city = form.City.value;
		var state = form.State.value;

		form.Zipcode.value = form.Zipcode.value.trim();
		var zipcode = form.Zipcode.value;
		
		var email = form.EmailAddress.value;
		var error = "";

		var emailReply = form.ReplyMethod[0].checked;
		var postalReply = form.ReplyMethod[1].checked;
		var noReply = form.ReplyMethod[2].checked;

		//###############################################################
		//####[  ACCENT CHARACTERS ]#####################################
		//###############################################################

		if (
			containsAccentCharacters( firstName )
			|| containsAccentCharacters( lastName )
			|| containsAccentCharacters( address )
			|| containsAccentCharacters( address2 )
			|| containsAccentCharacters( address3 )
			|| containsAccentCharacters( city )
			|| containsAccentCharacters( state )
		) {
			error = error + "Please Do Not Enter Accent Characters.  (\'ö\', etc...).\n\n";
		}

		//###############################################################
		//####[ / ACCENT CHARACTERS ]####################################
		//###############################################################

		// if the user requests a reply, make sure they have filled in the required fields
		if (! noReply) {
			if ( firstName.trim().length == 0 ) {
				error = error + "Please provide your First Name.\n";
			}

			if ( lastName.trim().length == 0 ) {
				error = error + "Please provide your Last Name.\n";
			}

			if ( address.trim().length == 0 ) {
				error = error + "Please provide your Address.\n";
			}

			// check if there is additional address for countries other than the US or Canada
			if ( address2.trim().length == 0 ) {
				if (( ! isDomesticUS( country) ) && ( country != "Canada" ) ) {
					if ( city.trim().length == 0 ) {
						error = error + "Please provide your City (or nearest city).\n";
					}
				}
			}

			// check if there is a city for the US or Canada
			if ( (city.trim().length == 0 ) && ( isDomesticUS( country) || (country == "Canada") ) ) {
				error = error + "Please provide your City.\n";
			}

			if ( (state.trim().length == 0) && isDomesticUS(country) ) {
				error = error + "Please provide your State/Province.\n";
			}

			if ( (state.trim().length == 0) && (country == "Canada")) {
				error = error + "Please provide your Province.\n";
			}

			if (isDomesticUS(country)) {
				if (! isNumeric(zipcode)) {
					error = error + "Please provide a Numeric Zip code.\n";
				}

				if (zipcode.trim().length < 5) {
					error = error + "Please provide your ZIP Code.\n";
				}
			} else if ((country == "Canada") && (zipcode.trim().length < 6 )) {
				error = error + "Please provide your Postal Code.\n";
			}

			if ( email.trim().length > 0 ) {
				if ( ! validEmail(email) ) {
					error = error + "Incorrect email address format.\nMust be following format:\n\n  name@domain.ext\n\nFor example: fred@aol.com";
				}
			} else if (emailReply) {
				error = error + "Please provide your E-mail address.\n";
			}
		}

		if ( isDomesticUS( country ) ) {
			if ( isOutLyingDomestic( country ) ) {
				form.NewState.value=form.Country.value;
			}

			form.NewCountry.value="US";
			country=form.NewCountry.value.trim();
		} else {
			//###################################################################
			// Due to a 5 line limitation for addresses, foreign addresses
			// are put into Address line 3.
			//###################################################################

			if ( country == "Canada" ) {
				if ( zipcode.indexOf(" ") == -1 ) {
					if ( zipcode.length == 6 ) {
						form.Zipcode.value=zipcode.substring(0,3)+" "+zipcode.substring(3);
					} else if ( zipcode.length == 7 ) {
						form.Zipcode.value=zipcode.substring(0,3)+" "+zipcode.substring(4);
					}
				}
			} else {
				form.ForeignAddress3.value=form.Zipcode.value+" "+form.City.value+" "+form.State.value;
			}
		}

		form.NewCountry.value= country.trim().toUpperCase();

		// third, determine if there is an error, and if so alert the user
		if ( error.trim().length != 0 ) {
			error = "To receive a reply from Silent Unity:\n\n" + error;
			alert(error);
			return false;
		}
	} catch(e) {
		alert("Failed To Validate Form Due To UnExpected RunTime Exception-["+e+"]");
		return false;
	}
	
	form.Submit.disabled=true;	
	return true;
}

function textCounter(field, countfield, maxlimit) {
	if (field.value.length > maxlimit) {
		// if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
		
		alert("Due to system requirements, you cannot enter more than " + maxlimit + " characters\n\nWe apologize for any inconvenience.");
	}
	
	// update 'characters left' counter
	countfield.value = maxlimit - field.value.length;
}

function updateStateSelect(stateField, states) {
	if (stateField.type == 'text') {
		var stateParent = stateField.parentNode;
		
		var newStateField = document.createElement('select');
		newStateField.name = stateField.name;
		newStateField.style.width = stateField.style.width;
		
		stateParent.insertBefore(newStateField, stateField);
		stateParent.removeChild(stateField);
		
		newStateField.id = newStateField.name;
		
		stateField = newStateField;
	}
	
	stateField.options.length = states.length;
	for (i = 0; i < states.length; i++) {
		if (i == 0) {
			 stateField.options[i] = new Option(states[i], '');
		} else {
			 stateField.options[i] = new Option(states[i], states[i]);
		}
	}
}

function updateStateText(stateField) {
	if (stateField.type != 'text') {
		var stateParent = stateField.parentNode;
		
		var newStateField = document.createElement('input');
		newStateField.type = 'text';
		newStateField.name = stateField.name;
		newStateField.style.width = stateField.style.width;
		
		stateParent.insertBefore(newStateField, stateField);
		stateParent.removeChild(stateField);
		
		newStateField.id = newStateField.name;
		
		stateField = newStateField;
	}
	
	stateField.value = '';
}

function processCountryChangeUS(stateField) {
	var states = new Array(
		"Select a State","AA","AE","AP","AL","AK","AZ","AR","CA","CO","CT","DE","DC","FL","GA","GU","HI","ID",
		"IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MO","MP","MS","MT","NE","NV","NH","NJ","NM","NY","NC",
		"ND","OH","OK","OR","PA","PR","RI","SD","SC","TN","TX","UT","VI","VA","VT","WA","WV","WI","WY"
	);
	
	updateStateSelect(stateField, states);
}

function processCountryChangeCanada(stateField) {
	var provinces = new Array(
		"Select a Province","AB","BC","MB","NB","NL","NT","NS","NU","ON","PE","PQ","SK","YT"
	);
	
	updateStateSelect(stateField, provinces);
}

function processCountryChange(countryField, stateField) {
	if (countryField.value == "Canada") {
		processCountryChangeCanada(stateField);
	} else if (countryField.value == "United States") {
		processCountryChangeUS(stateField);
	} else {
		updateStateText(stateField);
	}
}

function emailPage() {
	popupWindow("/EmailPage.html?title="+document.title, "_emailPage", null, null, 1, 1, 1, 1, 1);
}
	

