/**
 * Javascript functions Foodbrokers USA
 * 
 * http://www.foodbrokersusa.com
 * 
 */

function getDocId(docName) {
	/** 
	 * the modx document id's are different on the server than they are
	 * on our local development environment.
	 * easier to keep them here then spread out throught the file.
	 *
	 * set the dev or server flag here.
	 * srv = server
	 * dev = development
	 */
	
	var serverVars = 'srv';
	// var serverVars = 'dev';
	
	if (serverVars == 'srv') {
		var docHome 	= 1;
		var docLogin 	= 15;
		var docProfile 	= 19;
		var pwCheck		= 21;
		var docUpdatePw	= 22;
		var saveProfile = 19;
		var docDownloads = 20;
		var chkEmail	= 25;
		var getEmail	= 27;
		var authFP		= 24;
		var contactUs	= 29;
	}
	
	if (serverVars == 'dev') {
		var docHome 	= 1;
		var docLogin	= 15;
		var docProfile	= 18;
		var pwCheck		= 24;
		var docUpdatePw	= 25;
		// var saveProfile = 22;
		var saveProfile = 18;
		var docDownloads = 23;
		var chkEmail	= 21;
		var getEmail	= 23;
		var authFP		= 20;
		var contactUs	= 26;
	}
	
	switch(docName) {
		case 'home':
			return docHome;
			break;
		case 'login':
			return docLogin;
			break;
		case 'profile':
			return docProfile;
			break;
		case 'pwCheck':
			return pwCheck;
			break;
		case 'updatePw':
			return docUpdatePw;
			break;
		case 'saveProfile':
			return saveProfile;
			break;
		case 'downloads':
			return docDownloads;
			break;
		case 'chkEmail':
			return chkEmail;
			break;
		case 'getEmail':
			return getEmail;
			break;
		case 'authFP':
			return authFP;
			break;
		case 'contactUs':
			return contactUs;
			break;
		default:
			return false;
	}
	
}


function loginCheck(){

	// Show the corresponding Login action based on loginStatus cookie
	if (loginStatus()) {
		getAccountName("accountInfo");
		displayLogoutLink();
	} else {
		displayLoginLink();
	}

	return false;
}

function loginStatus() {
	
	// Get the Login Status Cookie
	var login = getFBCookie("loginStatus");
	if (login.length > 0) {
		cookie = login.split("=");
		if (cookie[1] == 1) {
			return true;
		} else {
			return false;
		}
	}
	
	// On fail return false
	return false;
}

function isSearchAvaliable(subForm) {
	if (!loginStatus()) {
		displayLoginLink();
		alert("Please login to search our database");
		return false;
	}
	
	if (!getExpirationDate('accountInfo')) {
		alert("Your membership has expired.  \nPlease renew to enable Search access.");
		return false;
	}
	
	var thisForm = document.getElementById(subForm);
	thisForm.submit();
	
	return true;
}

function isDownloadAvailable(docNum) {
	if (!loginStatus()) {
		displayLoginLink();
		alert("Please login to access the media on this page");
		return false;
	}
	
	if (!getExpirationDate('accountInfo')) {
		alert("Your membership has expired.  \nPlease renew to enable Download access.");
		return false;
	}
	
	var docSelect = docNum;
	var downloadPathDir = '/fbusa/assets/foodbrokersUSA/website/downloads/';
	var downloadFile = '';
	
	
	// define the file to download based on the button clicked
	if (docSelect == 1) {
		downloadFile = 'cpcw.xls';
	} else if (docSelect == 2) {
		downloadFile = 'npcs.xls';
	} else if (docSelect == 3) {
		downloadFile = 'fcs.xls';
	} else if (docSelect == 4) {
		downloadFile = 'dpm.xls';
	} else {
		// The document is not defined.
		alert("The document you've requested is not available");
		return false;
	}
	// send the request for the file to download
	window.location.href = downloadPathDir + downloadFile;
	
	return true;
}

function isNewAccountOk(subForm) {
	if (loginStatus() ) {
		alert("Please logout to register a new account");
		return false;
	} else {
		
		var thisForm = document.getElementById(subForm);
		thisForm.submit();
		return true;
	}
}

function getFBCookieValue(cookieName) {
	var fullCookie = getFBCookie(cookieName);
	if(fullCookie.length > 0) {
		kvCookie = fullCookie.split("=");
		
		return kvCookie[1];
	}
	// nothing to return
	return false;
}

function processLogout() {
	// unset the loginStatus cookeie and redirect the user to the home page.
	
	document.cookie = "loginStatus=; expires=Thu, 01-Jan-70 00:00:01 GMT" + "; path=/";
	document.cookie = "accountInfo=; expires=Thu, 01-Jan-70 00:00:01 GMT" + "; path=/";
	window.location.href = '?id='+ getDocId('home'); 
	return true;
}

function testLoginPswd(uid, pwd) {
	
	if (!uid || !pwd) {
		// one or both of the parameters are missing
		return false;
	}

	// responseCode indicates the results of the password auth (true/false)
	var responseCode = 0;
	
	var rec	= new ajaxRequest();
	var url = '?id=' + getDocId('pwCheck');
	var parms = 'username=' + uid + '&password=' + pwd;
	
	rec.open('POST', url, false);
	rec.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	rec.send(parms);
	
	if (rec.responseText == 'OK') {
		responseCode = 1;
	} else {
		responseCode = 0;
	}
	
	return responseCode;
}

function clearPwUpdaetErrorMsgs() {
	document.getElementById('pwMessage1').innerHTML = '';
	document.getElementById('pwMessage2').innerHTML = '';
	document.getElementById('pwMessage3').innerHTML = '';
	
	return true;
}

function updatePwdProcessor() {
	var currentPassword = document.getElementById('currentPasscode').value;
	var newPassword 	= document.getElementById('newPasscode').value;
	var confirmPassword = document.getElementById('confNewPasscode').value;
	var accountId 		= document.getElementById('pwdId').value;
	var message1	= document.getElementById('pwMessage1');
	var message2	= document.getElementById('pwMessage2');
	var message3	= document.getElementById('pwMessage3');
	
	// clear the message boxes before we begin.
	clearPwUpdaetErrorMsgs();
	
	// Check that the new password meets security criteria
	if (newPassword.length < 4) {
		message2.style.color = '#dd0000';
		message2.style.fontWeight = 'normal';
		message2.innerHTML = '<br/>New Password is too short';
		return false;
	}
	
	// Make sure the new password and the confirmation password match
	if (newPassword != confirmPassword) {
		message3.style.color = '#dd0000';
		message3.style.fontWeight = 'normal';
		message3.innerHTML = "<br/>Passwords do not match";
		return false;
	}
	
	if (testLoginPswd(accountId, currentPassword) == 1) {
		// password check was successful.
		// alert(currentPassword + '  ' + accountId);
		
		// update the password for the user.
		if (updateUserPwd(accountId, newPassword) == 1) {
			// password update successfull
			document.getElementById('currentPasscode').value = '';
			document.getElementById('newPasscode').value = '';
			document.getElementById('confNewPasscode').value = '';
			
			message1.style.color = '#00aa00';
			message1.style.fontWeight = 'normal';
			message1.innerHTML = "<br/>Password update Complete!";
			
			// clear the success message after 10 seconds
			setTimeout("clearPwUpdaetErrorMsgs()", 1500);
			
		} else {
			// password update failed
			alert('password check failed');
			return false;
		}
	} else {
		message1.style.color = '#dd0000';
		message1.style.fontWeight = 'normal';
		message1.innerHTML = "<br/>Password is incorrect!";
		return false;
	}
}

function updateUserPwd(uid, pwd) {
	// responseCode indicates the results of the password update operation
	var responseCode = 0;
	
	var req	= new ajaxRequest();
	var url = '?id=' + getDocId('updatePw');
	var parms = 'username=' + uid + '&password=' + pwd;
	
	req.open('POST', url, false);
	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	req.send(parms);
	
	if (req.responseText == 'OK') {
		return 1;
	} else {
		return 0;
	}
}



function requestPaymentForm(amount) {
	
	var payForm = document.getElementById('paymentForm');
	var formData = getTransactionFP(amount);
	var transaction = eval("(" + formData + ")");
	
	if (payForm != null) {
		
		payForm.method 					= "POST";
		payForm.action					= transaction.url;
		payForm.x_login.value 			= transaction.loginId;
		payForm.x_fp_hash.value 		= transaction.fp_hash;
		payForm.x_amount.value 			= transaction.amount;
		payForm.x_fp_timestamp.value 	= transaction.timestamp;
		payForm.x_fp_sequence.value 	= transaction.sequence;
		payForm.x_type.value 			= transaction.type;
		payForm.x_version.value 		= transaction.version;
		payForm.x_show_form.value 		= transaction.show_form;
		payForm.x_test_request.value 	= transaction.test_request;
		payForm.x_method.value 			= transaction.method;
		
		// submit the form to Autorize.net
		payForm.submit();
		
	} else {
		alert('Error: Form configuration');
		return false;
	}
	
	return true;
}

function getTransactionFP(transAmount) {
	var req = new ajaxRequest();
	var parms = 'amount=' + transAmount;
	
	req.open('GET', '?id=' + getDocId('authFP') + '&amount=' + transAmount, false);
	req.setRequestHeader("Content-Type", "application/x-www-form-urlencode");
	req.send(parms);
	
	if (req.responseText != 'Error') {
		// Get Fingerprint Succeeded.
		return req.responseText;
	} else {
		return false;
	}
	
	return false;
}

function saveProfileChanges() {
	
	document.profileForm.action = '?id=' + getDocId('saveProfile');
	
	if (document.getElementById('profile[busname]') == '') {
		alert('Busness Name cannot be empty');
		return false;
	}
	
	if (document.getElementById('email').value == '') {
		alert('Email cannot be empty');
		return false;
	}
	
	// Make sure the user has entered a valid email address
	if (!checkForValidEmail(document.getElementById('email').value)) {
		alert('Please Enter a Valid Email Address');
		return false;
	}
	
	document.profileForm.submit();
	
	return true;
	
}

function ajaxRequest() {
	var activexmodes = ["Msxml2.XMLHTTP","Microsoft.XMLHTTP"];
	
	if (window.ActiveXObject) {
		for (var i=0; i<activexmodes.length; i++) {
			try {
				return new ActiveXObject(activexmodes[i]);
			}
			catch (e) {
				// suppress error
			}
		}
	} else if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else {
		return false;
	}
	
	return true;
}

function processLogin() {
	// Set local variable for the login form.
	var loginForm = document.getElementById('LoginForm');

	// Send the form to the validator.
	if ( !validateLoginForm(loginForm.username.value, loginForm.password.value) ) {
		// The validation faild so we show the login link again.
		// loginCheck();
		displayLoginForm();
		return false;
	}
	
	// Request login authorization
	var url = '?id='+ getDocId('login');
	var username = encodeURIComponent(loginForm.username.value);
	var password = encodeURIComponent(loginForm.password.value);
	var parameteres = 'username='+username+'&password='+password;
	var loginRequest = new ajaxRequest();

	loginRequest.onreadystatechange = function() {
		if (loginRequest.readyState == 4) {
			if (loginRequest.status == 200 || window.location.href.indexOf("http") == -1) {
				if (loginRequest.responseText == 0) {
					// Auth failed send alert
					alert("Login Failed!");
				} else {
					
					// Set the login status
					if (!setFBCookie("loginStatus", "1", "/", "3")) {
						alter("Failed to Set login State!");
						return false;
					}
					
					// set the account information cookie for later use
					if (!setFBCookie("accountInfo", loginRequest.responseText, "/", "3")) {
						alter("Failed to Set Account Info");
						return false;
					}
					
					getAccountName("accountInfo");
					displayLogoutLink();
				}
			} else {
				alert("Response Code " + loginRequest.status );
			}
		}
	}
	
	loginRequest.open('POST', url, true);
	loginRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	loginRequest.send(parameteres);
	
	// loginCheck();
	return true;	
}

function getAccountName (cName) {
	
	var profile = "";
	var cookieData = getFBCookieValue(cName);
	var accInfo = eval("("+cookieData+")");
	var nameSpace = document.getElementById('accountName');
	var linkStyle = 'style="font-size: 7pt; text-decoration: none; border: solid; border-color: #008800; border-width: 1px; padding: 1px;"';
	var profileLink = '<a href="?id='+ getDocId('profile') +'&bid=' + accInfo.id + '" ' + linkStyle + '>Edit</a>';
	
	// Build the output string.
	if (accInfo.id != "") { profile += "<div style='text-align: right; padding-bottom: 4px;'>" + profileLink + "</div>"; }
	if (accInfo.name != "") { profile += "<div style='padding-bottom: 4px;'>" + accInfo.name + "</div>"; }
	if (accInfo.add1 != "") { profile += "<div style='font-size: 8pt;'>" + accInfo.add1 + "<div>"; }
	if (accInfo.city != "") { profile += "<div style='font-size: 8pt; padding-bottom: 10px;' >" + accInfo.city + ""; }
	if (accInfo.state != "") { profile += ", "  + accInfo.state + "</div>"; }
	
	nameSpace.innerHTML = profile;
}

function getExpirationDate (cName) {
	
	var cookieData = getFBCookieValue(cName);
	var accInfo = eval("("+cookieData+")");
	var date = new Date();

	if (accInfo.refKey < date.getTime()) {
		return false;
	}
	
	return true;
}
 
function getLoginId (cName) {
	var cookieData = getFBCookieValue(cname);
	var accInfo = eval("("+cookieData+")");
	
	return accInfo.id;
}

function sendContactUsMessage() {
	var contactUsForm = document.getElementById('msgForm');
	if (!checkForValidEmail(contactUsForm.msgFrom.value)) {
		alert('The email entered is not valid!' + "\n" + 'Please enter a valid email address.');
		return false;
	}
	
	var req = new ajaxRequest();
	var url = '?id=' + getDocId('contactUs');
	var parms = 'msgSubject=' + contactUsForm.msgSubject.value + 
				'&msgFrom=' + contactUsForm.msgFrom.value + 
				'&msgMessage=' + contactUsForm.msgMessage.value;
	
	req.open('POST', url, false);
	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	req.send(parms);
	
	if (req.responseText == 'MessageSent') {
		// no errors reported.
		document.getElementById("messageForm").style.display = 'none';
		document.getElementById("messageSent").style.display = 'inline';
		
		return true;
		
	} else {
		alert("Error Sending Message.  Please contact info@foodbrokersusa.com");
		// clear the form contents after form submission failure.
		contactUsForm.msgSubject.value = '';
		contactUsForm.msgFrom.value = '';
		contactUsForm.msgMessage.value = '';
		
		return false;
	}
	
}

function validateLoginForm (u, p) {
	
	if (!checkLoginLength(u)) {
		alert('Login ID must be 4 or more charaters in length');
		return false;
	}
	
	if (!checkPasswordLength(p)) {
		alert('Passowds cannot be empty');
		return false;
	}
	
	return true;
}

function forgotPassword () {
	var loginId = document.getElementById('forgotPasswordForm').loginId.value;
	if (!checkLoginLength(loginId)) {
		alert('Login ID must be 4 or more charaters in length');
		return false;
	}
	
	var req = new ajaxRequest();
	var url = '?id=' + getDocId('getEmail');
	var parms = 'loginId=' + loginId;
	
	req.open('POST', url, false);
	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	req.send(parms);
	
	if (req.responseText != 'FALSE') {
		alert('Your account information has been sent to the registered email address: ' + req.responseText);
		window.location.href = "?id=" + getDocId('home');
	} else {
		alert("We do not have an email address on file for the requested account\n\nPlease contact us at: 714-547-3321");
		window.location.href = "?id=" + getDocId('home');
		return false;
	}
	
}

function checkLoginLength (login) {
	if (login.length < 4) {
		return false;
	}
	
	return true; 
}

function checkPasswordLength (password) {
	if (password.length < 1) {
		return false;
	}
	
	return true;
}

function getFBCookie (cookieName) {
	
	if (document.cookie.length > 0 ) {
		start = document.cookie.indexOf(cookieName + "=");
		end   = document.cookie.indexOf("; ", start);
		if (end == -1) {
			end = document.cookie.length;
		}
		
		siteCookie = document.cookie.substring(start, end);	
		return siteCookie;
	}
	
	return "";
}

function setFBCookie (cName, cValue, cPath, cNumDays) {
	
	if (cName.length > 0 ) {
		// Create new Date object
		var expDate = new Date();
		
		// Add cNumDays to the expDate for this cookie
		var addDays = expDate.getTime() + (cNumDays * 24 * 60 * 60 * 1000); 
		expDate.setTime(addDays);
		
		// Create the cookie string to be stored in the browser
		var cookieStr = cName + "=" + cValue + ";path=" + cPath + ";expires=" + expDate.toGMTString();
		
		// cookie format: name=value;path=path;expires=miliseconds
		document.cookie = cookieStr;
		
		// setting the cookie was succesful.
		return true;
		
	} else {
		return false;
	}
	
}

function displayLogoutLink () {
	var outLink = document.getElementById('logoutLink');
	var inForm = document.getElementById('loginForm');
	var inLink = document.getElementById('loginLink');
	
	inForm.style.display = "none";
	inLink.style.display = "none";
		
	outLink.style.display = "inline";
	outLink.style.position = "absolute";
	outLink.style.right = "25px";
	outLink.style.bottom = "7px"
		
	return true;
}

function displayLoginLink () {
	var inForm = document.getElementById('loginForm');
	var inLink = document.getElementById('loginLink');
	var outLink = document.getElementById('logoutLink');
	
	inForm.style.display = "none";
	outLink.style.display = "none";
	
	inLink.style.display = "inline";
	inLink.style.position = "absolute";
	inLink.style.bottom = "7px";
	inLink.style.right = "25px";
	
	return true;
	
}

function displayLoginForm () {
	var inForm = document.getElementById('loginForm');
	var inLink = document.getElementById('loginLink');
	
	inLink.style.display = "none";
	
	inForm.style.display = "inline";
	inForm.style.position = "absolute";
	inForm.style.bottom = "2px";
	inForm.style.right = "13px";
	
	return true;
}

function toggleFormOptions (radioOpt) {
	
	if (!radioOpt) {
		// No options passed, return false
		return false;
	}
		
	var brokerFormOptions = document.getElementById('formBrokerSection');	
	var principalFormOptions = document.getElementById('formPrincipalSection');
	var memberForm = document.getElementById('membershipForm');
	
	if (radioOpt == 1 ) {
		// Turn on broker options
		brokerFormOptions.style.display = "inline";
		
		// Turn off Principal Options
		principalFormOptions.style.display = "none";	
	}
	
	if (radioOpt == 2) {
		// Turn on Principal Options
		principalFormOptions.style.display = "inline";

		// Turn off broker Options
		brokerFormOptions.style.display = "none";
	}
		
	return true;
}

function submitSearchForm(searchForm, showAll) {
	
	var sForm = document.getElementById(searchForm);
	if (showAll == 1) {
		sForm.showAll = 1;
	}
	
	sForm.method = "POST";
	sForm.submit();
}

function submitBusnessInfoForm() {
	
	var joinForm = document.getElementById('membershipForm');
		
	// Check for all other required fields.
	// Define Broker required form fields.
	var reqFields = new Array('busname','city','state','country','zipcode','phone','email');
	var fieldDisplay = new Array('Business Name','City','State','Country','Zip','Phone','Email');
	
	var errMsg = '';
	for (i=0; i < reqFields.length; i++) {
		
		if (!joinForm.elements[reqFields[i]].value) {
			errMsg = errMsg + '- ' + fieldDisplay[i] + '\n';
		}
	}
	
	if (errMsg != '') {
		var preMsg = 'The following fields are required:\n\n';
		alert(preMsg + errMsg);
		return false;	
	}
	
	// Make sure the user has entered a valid email address
	if(!checkForValidEmail(joinForm.elements['email'].value)) {
		alert('Please Enter a Valid Email Address');
		joinForm.elements['email'].focus();
		joinForm.elements['email'].select();
		return false;
	}

/*
 * Unique email addresses are no longer required
 
	if (!validateEmailAddress(joinForm.elements['email'].value)) {
		alert('The email address entered already exists!');
		joinForm.elements['email'].focus();
		joinForm.elements['email'].select();
		return false;
	}
*/		
	// No errors to report if we've gotten this far.  Submit the form.
	joinForm.method = "POST";
	joinForm.submit();
	
}

function validateEmailAddress(email) {
	/*
	 * Check the user provided email against email addresses
	 * already in the system. 
	 * 
	 * return false if the email already exists.
	 */
	
	var req = new ajaxRequest();
	var url = '?id=' + getDocId('chkEmail');
	var parms = 'email=' + email;
	
	req.open('POST', url, false);
	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	req.send(parms);
	
	if (req.responseText == 'OK') {
		return true;
		
	} else {
		return false;
	}
	
	return false;
}

function checkForValidEmail(email) {
	
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

	if(reg.test(email) == false) {
		return false;
	} else {
		return true;
	}
	
	return true;
}

function submitMarketInfoForm(){

	var joinForm = document.getElementById('membershipForm');
	
	// Check for all other required fields.
	if (joinForm.listingType.value == 0) {
		// Define Broker required form fields.
		var reqFields = new Array('markets', 'key_person_1');
		var fieldDisplay = new Array('Markets Covered', 'First Key Personnel');
	} else {
		var reqFields = new Array();
		var fieldDisplay = new Array();
	}
	
	var errMsg = '';
	for (i=0; i < reqFields.length; i++) {
		if (!joinForm.elements[reqFields[i]].value) {
			errMsg = errMsg + '- ' + fieldDisplay[i] + '\n';
		}
	}
	
	if (errMsg != '') {
		var preMsg = 'The following fields are required:\n\n';
		alert(preMsg + errMsg);
		return false;	
	}

	// No errors to report if we've gotten this far.  Submit the form.
	joinForm.method = "POST";
	joinForm.submit();
	
}

function submitAccountInfoForm() {
	
	var joinForm = document.getElementById('membershipForm');
	
	// check to make sure the password is long enough.
	if (joinForm.passcode.value.length < 4) {
		alert('Your password must be at least 4 charaters long');
		return false;
	}
	
	var re = new RegExp("[0-9]", "g");
	if ( !re.test(joinForm.passcode.value) ) {
		alert("Your password must contain at least 1 number (0-9)");
		return false;
	}
	
	// Check to make sure the password and the confirmation password match.
	if (joinForm.passcode.value != joinForm.confPass.value) {
		alert('The Password fields must match!');
		joinForm.passcode.focus();
		return false;
	}
	
	// No errors to report if we've gotten this far. Submit the form.
	joinForm.submit();
	
}


function countrySelect(countrySelect, fieldName, stateFieldName) {

	var countries = new Array(
		'US','United States', 'CA','Canada', 'UK','United Kingdom', 'AF','Afghanistan',
	    'AL','Albania', 'DZ','Algeria', 'AS','American Samoa', 'AD','Andorra',
	    'AO','Angola', 'AI','Anguilla', 'AQ','Antarctica', 'AG','Antigua and Barbuda',
	    'AR','Argentina', 'AM','Armenia', 'AW','Aruba', 'AU','Australia',
	    'AT','Austria', 'AZ','Azerbaijan', 'BS','Bahamas', 'BH','Bahrain',
	    'BD','Bangladesh', 'BB','Barbados', 'BY','Belarus', 'BE','Belgium',
	    'BZ','Belize', 'BJ','Benin', 'BM','Bermuda', 'BT','Bhutan',
	    'BO','Bolivia', 'BA','Bosnia-Herzegovina', 'BW','Botswana', 'BV','Bouvet Island',
	    'BR','Brazil', 'IO','British Indian Ocean Territory', 'BN','Brunei Darussalam',
	    'BG','Bulgaria', 'BF','Burkina Faso', 'BI','Burundi', 'KH','Cambodia',
	    'CM','Cameroon', 'CV','Cape Verde', 'KY','Cayman Islands', 'CF','Central African Republic',
	    'TD','Chad', 'CL','Chile', 'CN','China', 'CX','Christmas Island', 'CC','Cocos (Keeling) Islands',
	    'CO','Colombia', 'KM','Comoros', 'CG','Congo', 'CK','Cook Islands', 'CR','Costa Rica',
	    'CI',"Cote D'Ivoire", 'HR','Croatia', 'CU','Cuba', 'CY','Cyprus', 'CZ','Czech Republic',
	    'DK','Denmark', 'DJ','Djibouti', 'DM','Dominica', 'DO','Dominican Republic',
	    'TP','East Timor', 'EC','Ecuador', 'EG','Egypt', 'SV','El Salvador',
	    'GQ','Equatorial Guinea', 'EE','Estonia', 'ET','Ethiopia', 'FO','Faeroe Islands',
	    'FK','Falkland Islands (Malvinas)', 'FJ','Fiji', 'FI','Finland', 'FR','France',
	    'GF','French Guiana', 'PF','French Polynesia', 'TF','French Southern Territories',
	    'GA','Gabon', 'GM','Gambia', 'GE','Georgia', 'DE','Germany', 'GH','Ghana',
	    'GI','Gibraltar', 'GR','Greece', 'GL','Greenland', 'GD','Grenada', 'GP','Guadeloupe',
	    'GU','Guam', 'GT','Guatemala', 'GG','Guernsey, C.I.', 'GN','Guinea',
	    'GW','Guinea-Bissau', 'GY','Guyana', 'HT','Haiti', 'HM','Heard and McDonald Islands',
	    'HN','Honduras', 'HK','Hong Kong', 'HU','Hungary', 'IS','Iceland',
	    'IN','India', 'ID','Indonesia', 'IR','Iran (Islamic Republic of)',
	    'IQ','Iraq', 'IE','Ireland', 'IM','Isle of Man', 'IL','Israel',
	    'IT','Italy', 'JM','Jamaica', 'JP','Japan', 'JE','Jersey, C.I.',
	    'JO','Jordan', 'KZ','Kazakhstan', 'KE','Kenya', 'KI','Kiribati',
	    'KP',"Korea, Dem. People's Rep of", 'KR','Korea, Republic of',
	    'KW','Kuwait', 'KG','Kyrgyzstan', 'LA','Lao Peoples Democratic Republi',
	    'LV','Latvia', 'LB','Lebanon', 'LS','Lesotho', 'LR','Liberia',
	    'LY','Libyan Arab Jamahiriya', 'LI','Liechtenstein',
	    'LT','Lithuania', 'LU','Luxembourg', 'MO','Macau',
	    'MG','Madagascar', 'MW','Malawi', 'MY','Malaysia', 'MV','Maldives',
	    'ML','Mali', 'MT','Malta', 'MH','Marshall Islands',
	    'MQ','Martinique', 'MR','Mauritania', 'MU','Mauritius',
	    'MX','Mexico', 'FM','Micronesia, Fed. States of', 'MD','Moldova, Republic of',
	    'MC','Monaco', 'MN','Mongolia', 'MS','Montserrat', 'MA','Morocco',
	    'MZ','Mozambique', 'MM','Myanmar', 'NA','Namibia', 'NR','Nauru',
	    'NP','Nepal', 'AN','Netherland Antilles', 'NL','Netherlands',
	    'NT','Neutral Zone (Saudi/Iraq)', 'NC','New Caledonia',
	    'NZ','New Zealand', 'NI','Nicaragua', 'NE','Niger', 'NG','Nigeria',
	    'NU','Niue', 'NF','Norfolk Island', 'MP','Northern Mariana Islands',
	    'NO','Norway', 'OM','Oman', 'PK','Pakistan', 'PW','Palau',
	    'PA','Panama', 'PZ','Panama Canal Zone', 'PG','Papua New Guinea',
	    'PY','Paraguay', 'PE','Peru', 'PH','Philippines', 'PN','Pitcairn',
	    'PL','Poland', 'PT','Portugal', 'PR','Puerto Rico', 'QA','Qatar',
	    'RE','Reunion', 'RO','Romania', 'RU','Russian Federation',
	    'RW','Rwanda', 'KN','Saint Kitts and Nevis', 'LC','Saint Lucia',
	    'WS','Samoa', 'SM','San Marino', 'ST','Sao Tome and Principe',
	    'SA','Saudi Arabia', 'SN','Senegal', 'SC','Seychelles', 'SL','Sierra Leone',
	    'SG','Singapore', 'SK','Slovakia', 'SI','Slovenia', 'SB','Solomon Islands',
	    'SO','Somalia', 'ZA','South Africa', 'ES','Spain', 'LK','Sri Lanka',
	    'SH','St. Helena', 'PM','St. Pierre and Miquelon', 'VC','St. Vincent and the Grenadines',
	    'SD','Sudan', 'SR','Suriname', 'SJ','Svalbard and Jan Mayen Islands',
	    'SZ','Swaziland', 'SE','Sweden', 'CH','Switzerland', 'SY','Syrian Arab Republic',
	    'TW','Taiwan', 'TJ','Tajikistan', 'TZ','Tanzania, United Republic of',
	    'TH','Thailand', 'TG','Togo', 'TK','Tokelau', 'TO','Tonga',
	    'TT','Trinidad and Tobago', 'TN','Tunisia', 'TR','Turkey',
	    'TM','Turkmenistan', 'TC','Turks and Caicos Islands',
	    'TV','Tuvalu', 'AE','U.A.E.', 'UM','U.S.Minor Outlying Islands',
	    'UG','Uganda', 'UA','Ukraine', 'UY','Uruguay',
	    'UZ','Uzbekistan', 'VU','Vanuatu', 'VA','Vatican City State',
	    'VE','Venezuela', 'VN','Viet Nam', 'VG','Virgin Islands (British)',
	    'VI','Virgin Islands, U.S.', 'WF','Wallis and Futuna Islands',
	    'EH','Western Sahara', 'YE','Yemen, Republic of', 'YU','Yugoslavia',
	    'ZR','Zaire', 'ZM','Zambia', 'ZW','Zimbabwe'
	);
	
	var countrySelectObj = document.createElement('SELECT');
	countrySelectObj.setAttribute('name', fieldName);
	countrySelectObj.setAttribute('onchange', 
								  "stateDisplayOptions('', this.options[this.selectedIndex].value, '" + stateFieldName + "')");
	// countrySelectObj.options[countrySelectObj.options.length] = new Option('', ' ', false);
	
	for (var i=0; i<countries.length; i=i+2) {
		if (countrySelect == countries[i+1]) {
			countrySelectObj.options[countrySelectObj.options.length] = new Option(countries[i+1], countries[i+1], true);
		} else {
			countrySelectObj.options[countrySelectObj.options.length] = new Option(countries[i+1], countries[i+1], false);
		}
	}
	
	document.getElementById('inputBoxCountry').appendChild(countrySelectObj);
	
	var reqNotice = document.createElement('SPAN');
	reqNotice.setAttribute('class', 'reqNotice');
	reqNotice.innerHTML = 'Required';
	
	document.getElementById('inputBoxCountry').appendChild(reqNotice);
	
}

function stateSelect(stateSel, fieldName) {
	
	var states = new Array(
		  'AL' ,'Alabama', 'AK' ,'Alaska', 'AZ' ,'Arizona',
		  'AR' ,'Arkansas', 'CA' ,'California', 'CO' ,'Colorado', 'CT' ,'Connecticut',
		  'DE' ,'Delaware', 'DC' ,'District of Columbia', 'FL' ,'Florida',
		  'GA' ,'Georgia', 'HI' ,'Hawaii', 'ID' ,'Idaho',
		  'IL' ,'Illinois', 'IN' ,'Indiana', 'IA' ,'Iowa', 'KS' ,'Kansas',
		  'KY' ,'Kentucky', 'LA' ,'Louisiana', 'ME' ,'Maine',
		  'MD' ,'Maryland', 'MA' ,'Massachusetts', 'MI' ,'Michigan', 'MN' ,'Minnesota',
		  'MS' ,'Mississippi', 'MO' ,'Missouri', 'MT' ,'Montana', 'NE' ,'Nebraska',
		  'NV' ,'Nevada', 'NH' ,'New Hampshire', 'NJ' ,'New Jersey', 'NM' ,'New Mexico',
		  'NY' ,'New York', 'NC' ,'North Carolina', 'ND' ,'North Dakota', 'OH' ,'Ohio',
		  'OK' ,'Oklahoma', 'OR' ,'Oregon', 'PA' ,'Pennsylvania',
		  'PR' ,'Puerto Rico', 'RI' ,'Rhode Island', 'SC' ,'South Carolina', 'SD' ,'South Dakota',
		  'TN' ,'Tennessee', 'TX' ,'Texas', 'UT' ,'Utah', 'VT' ,'Vermont',
		  'VI' ,'Virgin Island', 'VA' ,'Virginia', 'WA' ,'Washington', 'WV' ,'West Virginia',
		  'WI' ,'Wisconsin', 'WY' ,'Wyoming'
		);

	var stateSelectObj = document.createElement('SELECT');
	stateSelectObj.setAttribute('name', fieldName);
	stateSelectObj.options[stateSelectObj.options.length] = new Option('', '', false);
	
	for (var i=0; i < states.length; i=i+2 ) {
		
		if (stateSel == states[i]) {
			stateSelectObj.options[stateSelectObj.options.length] = new Option(states[i+1], states[i], true);
		} else {
			stateSelectObj.options[stateSelectObj.options.length] = new Option(states[i+1], states[i], false);
		}
	}	
	
	document.getElementById('inputBoxState').appendChild(stateSelectObj);
	
	var reqNotice = document.createElement('SPAN');
	reqNotice.setAttribute('class', 'reqNotice');
	reqNotice.innerHTML = 'Required';
	
	document.getElementById('inputBoxState').appendChild(reqNotice);
}

function stateTextBox (stateVal, fieldName) {
	var stateBoxObj = document.createElement('INPUT');
	stateBoxObj.setAttribute('type', 'text');
	stateBoxObj.setAttribute('class', 'inputBox');
	stateBoxObj.setAttribute('size', '25');
	stateBoxObj.setAttribute('name', fieldName);
	stateBoxObj.setAttribute('maxlength', '45');
	stateBoxObj.setAttribute('value', stateVal);
	
	document.getElementById('inputBoxState').appendChild(stateBoxObj);
	
	var reqNotice = document.createElement('SPAN');
	reqNotice.setAttribute('class', 'reqNotice');
	reqNotice.innerHTML = 'Required';
	
	document.getElementById('inputBoxState').appendChild(reqNotice);
}

function stateDisplayOptions(stateVal, countryVal, stateFieldName) {
	var stateBlock = document.getElementById('stateOptionBlock');
	var stateFormElem = document.getElementById('inputBoxState');
	
	try {
		stateFormElem.removeChild(stateFormElem.firstChild);
		stateFormElem.removeChild(stateFormElem.lastChild);
	} catch (err) {
		// Exception: No Child to remove, nothing to do here.
	}
	
	if (countryVal.length == 0) {
		countryVal = 'United States';
	}
	
	if (countryVal.length < 2) {
		// alert(countryVal.length);
		
	} else if (countryVal != 'United States') {
		// US country selected.  Display a dropdown list of US States.
		stateTextBox(stateVal, stateFieldName);
	} else if (countryVal == 'United States') {
		// Non US country selected.  Display a text box for entry
		stateSelect(stateVal, stateFieldName);
	}
}

function loadSelectOptions(stateVal, countryVal, fieldPrefix) {
	var stateBlock = document.getElementById('stateOptionBlock');
	var stateFormElem = document.getElementById('inputBoxState');
	
	if (countryVal.length == 0) {
		countryVal = 'United States';
	}
	
	try {
		stateFormElem.removeChild(stateFormElem.firstChild);
		stateFormElem.removeChild(stateFormElem.lastChild);
	} catch (err) {
		// Exception: No Child to remove, nothing to do here.
		// alert('Exception');
	}
	
	if (fieldPrefix.length > 0) {
		countryFieldName = fieldPrefix + '[country]';
		stateFieldName = fieldPrefix + '[state]';
	} else {
		countryFieldName = 'country';
		stateFieldName = 'state';
	}
	
	countrySelect(countryVal, countryFieldName, stateFieldName);
	stateDisplayOptions(stateVal, countryVal, stateFieldName);
	return true;
}



