//This function ensures that for each name entered, the ethnicity is also entered
var count = 0;

function checkNames() {
	for(var i=0; i<6; i++) {
	   //Name is not specified
	   if(trimString(document.getElementById("partymembernames"+i).value) == "") {
		   // Throw an alert
		   if(trimString(document.getElementById("ethnicity"+i).value) != "" && trimString(document.getElementById("agegroup"+i).value) != "") {
			  alert(" Please enter the Names for all the people in your party.");	
			  return false;
		   }
	   }
	}
	return true;	
}


function checkEthnicity() {
	for(var i=0; i<6; i++) {
	   //Name is specified
	   if(trimString(document.getElementById("partymembernames"+i).value) != "") {
		   //If Ethnicity not specified, throw an alert
		   if(trimString(document.getElementById("ethnicity"+i).value) == "") {
			  alert(" Please select the Ethnicity for " + document.getElementById("partymembernames"+i).value);	
			  return false;
		   }
	   }
	}
	return true;	
}

//This function ensures that for each name entered, the ethnicity is also entered
function checkAgegroup() {
	for(var i=0; i<6; i++) {
	   //Name is specified
	   if(trimString(document.getElementById("partymembernames"+i).value) != "") {
		   //If Age group is not specified, throw an alert
		   if(trimString(document.getElementById("agegroup"+i).value) == "") {
			  alert(" Please select the Age Group for " + document.getElementById("partymembernames"+i).value);	
			  return false;
		   }
	   }
	}
	return true;	
}

// Returns false if the field is empty, null, or has the string "null", and pops up
// the message passed to the function
function isNotNullOrEmptyString(fieldName, message) {	
	if (isNullOrEmpty(document.getElementById(fieldName).value)) {	
		alert(message);		
		return false;
	}
	return true;
}
// general purpose function to see if an input value has been
// entered at all or if the input value has a value "null"
function isNullOrEmpty(inputStr) {
	// trim; remove leading and trailing spaces
	var trimmedValue = trimString(inputStr);
	if (isEmpty(trimmedValue) || trimmedValue == "null") {
		return true;
	}
	return false;
}

//Remove leading and trailing spaces
function trimString(sInString) {
  sInString = sInString.replace( /^\s+/g, "" );// strip leading
  return sInString.replace( /\s+$/g, "" );// strip trailing
}

// general purpose function to see if an input value has been
// entered at all
function isEmpty(inputStr) {
	if (inputStr == null || inputStr == "") {
		return true;
	}
	return false;
}

// Validates the email entered.
function validateEmail(fieldValue){
   // The invalid characters that should not be used in an email address
   var invalidChars = " /:,;"; 
   var emailAddress = fieldValue;
   
   var atPosition = emailAddress.indexOf("@",1);
   var periodPosition = emailAddress.indexOf(".",atPosition);
   
   if (isNullOrEmpty(emailAddress)){
      return false;
   }
   // Checks for the invalid characters listed above.
   for (var i=0; i<invalidChars.length; i++){
      badChar = invalidChars.charAt(i);
	  if (emailAddress.indexOf(badChar,0) > -1){
	     return false;		 
	  }
   }

   if (atPosition == -1){ // Checks for the @
      return false;
   }

   if (emailAddress.indexOf("@",atPosition + 1) > -1){ // Makes sure there is one @
      return false;
   }
   if (periodPosition == -1){ // Makes sure there is a period after the @ 
      return false;
   }
   // Makes sure there is at least 2 characters after the period
   if ((periodPosition + 3) > emailAddress.length){ 
      return false;
   }
   
   return true;
}

// function used to check email and display message
function isValidEmail(fieldname, msg) {
	if (!validateEmail(document.getElementById(fieldname).value)) {
		alert(msg);
		return false;
	}
	return true;
}
//Compare two fields to ensure that if field1 value is not null or empty string
// then the field2 value must not be null or an empty string
function compareFieldValues(field1, field2, field3, message) {
	//Check whether field1 value is not null or empty string
	if(!isNullOrEmpty(document.getElementById(field1).value) || !isNullOrEmpty(document.getElementById(field2).value)) {
		//Check whether field2 value is null or empty string
		if(isNullOrEmpty(document.getElementById(field3).value)) {
			//Display error message
			alert(message + document.getElementById(field1).value + " " + document.getElementById(field2).value);
			return false;
		}	
	} 
	return true;
} 

// Returns false if the field has a value that is not a number and pops up
// the message passed to the function
function isNonNegativeNumber(fieldName, message) {
	if (isNumber(document.getElementById(fieldName).value)) {
		return true;
	}
	alert(message);
	document.getElementById(fieldName).value = "";
	return false;
}

// general purpose function to see if a suspected numeric input
// is a positive integer
function isPosInteger(fieldName, message) {
	inputStr = document.getElementById(fieldName).value;
	for (var i = 0; i < inputStr.length; i++) {
		var oneChar = inputStr.charAt(i);
		if (oneChar < "0" || oneChar > "9") {
			// clear the number field
			document.getElementById(fieldName).value = "";
			alert(message);
			return false;
		}
	}
	return true;
}

// function to update the cost of registration for a person based
// based on their age group
function updateAmount(idValue) {
	var amount = 0;
	var rate = 0;
	ageGroupCombo = document.getElementById("agegroup" + idValue);
	ageGroupComboValue = ageGroupCombo.options[ageGroupCombo.selectedIndex].value
	//alert("The age group combo value is " + ageGroupComboValue);
	// check that a name has been entered
	if (isNullOrEmpty(document.getElementById("partymembernames" + idValue).value)) {
		alert("Please enter a name before selecting an age group");
		ageGroupCombo[0].selected = "1";
		if(ageGroupCombo.options[ageGroupCombo.selectedIndex].value != "") {
			ageGroupCombo[1].selected = "1"; // <select one> option
		}
		document.getElementById("partymembernames" + idValue).focus();	
		return;
	} 
	// a name has been entered so check which group has been selected
	if(ageGroupComboValue == "Toddlers") {
		rate = new Number(document.getElementById("toddler_fee").value);
	} else if(ageGroupComboValue == "Children") {
		rate = new Number(document.getElementById("children_fee").value);
	} else if (ageGroupComboValue == "Youth") {
		rate = new Number(document.getElementById("youth_fee").value);
	} else if (ageGroupComboValue == "Students") {
		rate = new Number(document.getElementById("student_fee").value);
	} else if (ageGroupComboValue == "Adults") {
		rate = new Number(document.getElementById("adult_fee").value);
	} else {
		rate = 0;	
	}
	//alert("The amount is " + rate)
	amount = amount + rate ;
	document.getElementById("amount" + idValue).innerHTML = amount;
	// update hidden field
	document.getElementById("subtotal" + idValue).value = amount;
	updateTotalAmount();
}

// function to update the total amount for the registration
function updateTotalAmount() {
	// the registration amount for the person doing this registration
	var totalAmount = 0;
	
	var additionalPersonsCount = 6;
	for (var i=0; i < additionalPersonsCount; i++) {
		// find the amount for each person in the payer's party	
		if (isNullOrEmpty(document.getElementById("amount" + i).innerHTML)) {
			// do nothing
		} else {				
			totalAmount = totalAmount + new Number(document.getElementById("amount" + i).innerHTML);
		}
	}	
	// Display the total registration amount
	document.getElementById("totalregistrationfeespayment").innerHTML = "US$ " + totalAmount;
	//Update the hidden field  totalregistrationfees with with calculated amount
	document.getElementById("totalregistrationfees").value = totalAmount;
	// add the donation amount
	totalAmount = totalAmount + new Number(document.getElementById("donation").value);
	
	// Update the total amount to be paid
	document.getElementById("totalPayment").innerHTML = "US$ " + totalAmount;
	// update hidden field with total amount
	document.getElementById("totalamount").value = totalAmount;
}

// function to open a pop-up window with specific width
function openPopUpWindow(URL) {
aWindow=window.open(URL,"newwindow","toolbar=no,scrollbars=no,status=no,location=no,resizable=no,menubar=no,width=350,height=200,left=700,top=300");
}
// adds the person responsible for registeration to the party
function addPersonResponsibleToParty() {
	// Always overwrite the person responsible for the registration
	document.getElementById("partymembernames0").value = document.getElementById("firstname").value + " " + document.getElementById("lastname").value;
		// Set the "above 18 years" combo as the default for person responsible for registration and party
		amountCombo = document.getElementById("agegroup0");
		amountCombo[5].selected = "1";
		// update the total amount
		updateAmount(0); // the parameter passed is the id of the first combo in person's party
		//Set the ethinicity of the person responsible for payment in the group to the option selected
		document.getElementById("ethnicity0").value = document.getElementById("payerethnicity").value;
}

// add firstname of payer to list of people in party
function addPayerFirstName() {
	// Always overwrite the person responsible for the registration
	document.getElementById("partymembernames0").value = document.getElementById("firstname").value + " " + document.getElementById("lastname").value;
		
}

function show(thisPic, replacedPic) {	
	document.getElementById(replacedPic).src= myPix[thisPic];	
	matchPictureWithCaption(thisPic, replacedPic);
}

// set default picture
function setDefaultPicture(thisPic){
	defaultPicture = thisPic;
	show(defaultPicture, "myPicture");
}

// function to match picture with caption
function matchPictureWithCaption(picID, replacedPic){
	captionText = document.getElementById(picID).innerHTML;	
	document.getElementById(replacedPic+ "_text").innerHTML= captionText;
}

/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//      Videos Javascript                     //
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
function openVideoWindow(videoURL) {
	var URL = "../audiogallery/playvideo.php?id=" + videoURL;
	aWindow=window.open(URL,"video_window","toolbar=no,scrollbars=no,status=no,resizable=no,menubar=no,width=450,height=475");
}

// function to ensure that at least one checkbox has been selected
function checkSelection() {
   count = 0;
   for (var i=0; i < document.forms[0].elements.length; i++) {
      if (document.forms[0].elements[i].checked) {
	     count++;
	  }
   }
   if (count == 0) {
      alert("Please select the person you want to see at Ttabamiruka");
	  return false;
   }
   return true;
}
//This function checks whether three of the four check boxes are checked and return an error
//message if all four are checked.
// function to ensure that at only one checkbox has been selected
function checkNumberofSelectedItems() {
	
	if (checkSelection()) {
      	if (count > 3) {
	    	alert("Only Three items can be selected");
			return false;
	  	}
		
	} return true;
	
	return false;
} 
// This function validates the Ttabamiruka registration number which is of the format
// TTAB-2007-XXX

/*function validateRegistrationNumber(fieldName) {
	var regno = document.getElementbyId(fieldName).value;
		// check that the registration number contains TTAB
		if (navigator.userAgent.indexOf("TTAB") == -1) {
			alert('Wrong reg no');
			return false;
		}
		// check that the registration number contains 2007
		
		return true;
		
}*/

//general purpose function to see if a suspected numeric input
//is a positive or negative number
function isNumber(inputVal){
	oneDecimal =false;
	inputStr =inputVal.toString();
	for (var i =0; i <inputStr.length; i++){
		var oneChar = inputStr.charAt(i);
		if (i == 0 && oneChar == "+"){
			continue;
		}
		if (oneChar == "." && !oneDecimal){
			oneDecimal = true;
			continue;
		}
		if (oneChar < "0" || oneChar > "9"){
			return false;
		}
	}
	return true;
}


// Validates the registration number entered.
function validateRegistrationNumber(fieldValue){
  // var regno = "TTAB";
   var regno = fieldValue;
   var firstChar = regno.indexOf("TTAB",0);
   var firstDash = regno.indexOf("-",1);
   var year = regno.indexOf("2007",firstDash);
   var secondDash = regno.indexOf("-",year);

   //Check whther the first charater is TTAB
   if (firstChar == -1){
	  //alert('Invalid Regitration Number, Please enter a valid Regitration Number');
	  return false;
	}   
   // Checks for the dash 
   if (firstDash == -1){ 
      //alert('Invalid Regitration Number, Please enter a valid Regitration Number');
	  return false;
   }
   // Makes sure there is a year(2007) after the dash 
   if (year == -1){ 
      //alert('Invalid Regitration Number, Please enter a valid Regitration Number');
	  return false;
   }
    // Makes sure there is a dash after the year 
   if (secondDash == -1){
      //alert('Please enter another dash after the year');
	  return false;
   }
   // Makes sure there is at least 2 characters after the last dash
   if ((secondDash + 3) > regno.length){ 
      //alert('Please enter atleaset three character after the last dash ');
	  return false;
   }
  
   return true;
}

// function used to check the registration number
function isValidateRegistrationNumber(fieldname, msg) {
	if (!validateRegistrationNumber(document.getElementById(fieldname).value)) {
		alert(msg);
		return false;
	}
	return true;
}

// function to open a pop-up window
function openImageWindow(height, width, URL) {
	aWindow=window.open(URL,"awindow","toolbar=no,scrollbars=yes,status=no,resizable=yes,menubar=no,left=100,top=100,height=" + height + ",width="+ width);
}

// function to open a comment pop-up window
function openCommentWindow(height, width, URL) {
	aWindow=window.open(URL,"awindow","toolbar=no,scrollbars=yes,status=no,resizable=yes,menubar=no,left=100,top=100,height=" + height + ",width="+ width);
}

// JavaScript Document
function showTabIfVisible(mname, shown) {
	if (document.getElementById(mname+'_layer').style.visibility == (shown ? 'inherit' : 'hidden')) return;
		document.getElementById(mname+'lnk').className = shown ? 'bgonphototabid' : 'bgoffphototabid';
		document.getElementById(mname+'txt').className = shown ? 'smalltextnolink' : 'photolinks';
		document.getElementById(mname+'_layer').style.zIndex = shown ? 0 : -1;
		document.getElementById(mname+'_layer').style.visibility = shown ? 'inherit' : 'hidden';		
}

function showTab(lname) {
   showTabIfVisible('tab1', lname == 'tab1');
   showTabIfVisible('tab2', lname == 'tab2');
   showTabIfVisible('tab3', lname == 'tab3');
	showTabIfVisible('tab4', lname == 'tab4');
   
}
// open a window to display a list so that it can be printed
// open window
function openPrintList(redundantcolumns, pagetitle) { 
  fileName = "printerfriendly.php?columncheck=" +redundantcolumns + "&printoption=" + document.getElementById("printselect").value + "&pagetitle="+ pagetitle;
  // To specify the window characteristics edit the "features" variable below:
  // width - width of the window
  // height - height of the window
  // scrollbar - "yes" for scrollbars, "no" for no scrollbars
  // left - number of pixels from left of screen
  // top - number of pixels from top of screen
  features = "width=600,height=400,left=100,top=130,resizable=1, scrollbars=1,alwaysRaised=1";
  printwindow = window.open(fileName,"printWin", features);
  printwindow.focus();   
}

/* This script and many more are available free online at
The JavaScript Source :: http://javascript.internet.com
Created by: Down Home Consulting :: http://downhomeconsulting.com */

/*
Country State Drop Downs v1.0.
(c) Copyright 2005 Down Home Consulting, Inc.
www.DownHomeConsulting.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, itness for a particular purpose and noninfringement. in no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software.

*/



// State table
//
// To edit the list, just delete a line or add a line. Order is important.
// The order displayed here is the order it appears on the drop down.
//
var state = '\
US:AK:Alaska|\
US:AL:Alabama|\
US:AR:Arkansas|\
US:AS:American Samoa|\
US:AZ:Arizona|\
US:CA:California|\
US:CO:Colorado|\
US:CT:Connecticut|\
US:DC:D.C.|\
US:DE:Delaware|\
US:FL:Florida|\
US:FM:Micronesia|\
US:GA:Georgia|\
US:GU:Guam|\
US:HI:Hawaii|\
US:IA:Iowa|\
US:ID:Idaho|\
US:IL:Illinois|\
US:IN:Indiana|\
US:KS:Kansas|\
US:KY:Kentucky|\
US:LA:Louisiana|\
US:MA:Massachusetts|\
US:MD:Maryland|\
US:ME:Maine|\
US:MH:Marshall Islands|\
US:MI:Michigan|\
US:MN:Minnesota|\
US:MO:Missouri|\
US:MP:Marianas|\
US:MS:Mississippi|\
US:MT:Montana|\
US:NC:North Carolina|\
US:ND:North Dakota|\
US:NE:Nebraska|\
US:NH:New Hampshire|\
US:NJ:New Jersey|\
US:NM:New Mexico|\
US:NV:Nevada|\
US:NY:New York|\
US:OH:Ohio|\
US:OK:Oklahoma|\
US:OR:Oregon|\
US:PA:Pennsylvania|\
US:PR:Puerto Rico|\
US:PW:Palau|\
US:RI:Rhode Island|\
US:SC:South Carolina|\
US:SD:South Dakota|\
US:TN:Tennessee|\
US:TX:Texas|\
US:UT:Utah|\
US:VA:Virginia|\
US:VI:Virgin Islands|\
US:VT:Vermont|\
US:WA:Washington|\
US:WI:Wisconsin|\
US:WV:West Virginia|\
US:WY:Wyoming|\
US:AA:Military Americas|\
US:AE:Military Europe/ME/Canada|\
US:AP:Military Pacific|\
CA:AB:Alberta|\
CA:MB:Manitoba|\
CA:AB:Alberta|\
CA:BC:British Columbia|\
CA:MB:Manitoba|\
CA:NB:New Brunswick|\
CA:NL:Newfoundland and Labrador|\
CA:NS:Nova Scotia|\
CA:NT:Northwest Territories|\
CA:NU:Nunavut|\
CA:ON:Ontario|\
CA:PE:Prince Edward Island|\
CA:QC:Quebec|\
CA:SK:Saskatchewan|\
CA:YT:Yukon Territory|\
AU:AAT:Australian Antarctic Territory|\
AU:ACT:Australian Capital Territory|\
AU:NT:Northern Territory|\
AU:NSW:New South Wales|\
AU:QLD:Queensland|\
AU:SA:South Australia|\
AU:TAS:Tasmania|\
AU:VIC:Victoria|\
AU:WA:Western Australia|\
BR:AC:Acre|\
BR:AL:Alagoas|\
BR:AM:Amazonas|\
BR:AP:Amapa|\
BR:BA:Baia|\
BR:CE:Ceara|\
BR:DF:Distrito Federal|\
BR:ES:Espirito Santo|\
BR:FN:Fernando de Noronha|\
BR:GO:Goias|\
BR:MA:Maranhao|\
BR:MG:Minas Gerais|\
BR:MS:Mato Grosso do Sul|\
BR:MT:Mato Grosso|\
BR:PA:Para|\
BR:PB:Paraiba|\
BR:PE:Pernambuco|\
BR:PI:Piaui|\
BR:PR:Parana|\
BR:RJ:Rio de Janeiro|\
BR:RN:Rio Grande do Norte|\
BR:RO:Rondonia|\
BR:RR:Roraima|\
BR:RS:Rio Grande do Sul|\
BR:SC:Santa Catarina|\
BR:SE:Sergipe|\
BR:SP:Sao Paulo|\
BR:TO:Tocatins|\
NL:DR:Drente|\
NL:FL:Flevoland|\
NL:FR:Friesland|\
NL:GL:Gelderland|\
NL:GR:Groningen|\
NL:LB:Limburg|\
NL:NB:Noord Brabant|\
NL:NH:Noord Holland|\
NL:OV:Overijssel|\
NL:UT:Utrecht|\
NL:ZH:Zuid Holland|\
NL:ZL:Zeeland|\
UK:AVON:Avon|\
UK:BEDS:Bedfordshire|\
UK:BERKS:Berkshire|\
UK:BUCKS:Buckinghamshire|\
UK:CAMBS:Cambridgeshire|\
UK:CHESH:Cheshire|\
UK:CLEVE:Cleveland|\
UK:CORN:Cornwall|\
UK:CUMB:Cumbria|\
UK:DERBY:Derbyshire|\
UK:DEVON:Devon|\
UK:DORSET:Dorset|\
UK:DURHAM:Durham|\
UK:ESSEX:Essex|\
UK:GLOUS:Gloucestershire|\
UK:GLONDON:Greater London|\
UK:GMANCH:Greater Manchester|\
UK:HANTS:Hampshire|\
UK:HERWOR:Hereford & Worcestershire|\
UK:HERTS:Hertfordshire|\
UK:HUMBER:Humberside|\
UK:IOM:Isle of Man|\
UK:IOW:Isle of Wight|\
UK:KENT:Kent|\
UK:LANCS:Lancashire|\
UK:LEICS:Leicestershire|\
UK:LINCS:Lincolnshire|\
UK:MERSEY:Merseyside|\
UK:NORF:Norfolk|\
UK:NHANTS:Northamptonshire|\
UK:NTHUMB:Northumberland|\
UK:NOTTS:Nottinghamshire|\
UK:OXON:Oxfordshire|\
UK:SHROPS:Shropshire|\
UK:SOM:Somerset|\
UK:STAFFS:Staffordshire|\
UK:SUFF:Suffolk|\
UK:SURREY:Surrey|\
UK:SUSS:Sussex|\
UK:WARKS:Warwickshire|\
UK:WMID:West Midlands|\
UK:WILTS:Wiltshire|\
UK:YORK:Yorkshire|\
EI:CO ANTRIM:County Antrim|\
EI:CO ARMAGH:County Armagh|\
EI:CO DOWN:County Down|\
EI:CO FERMANAGH:County Fermanagh|\
EI:CO DERRY:County Londonderry|\
EI:CO TYRONE:County Tyrone|\
EI:CO CAVAN:County Cavan|\
EI:CO DONEGAL:County Donegal|\
EI:CO MONAGHAN:County Monaghan|\
EI:CO DUBLIN:County Dublin|\
EI:CO CARLOW:County Carlow|\
EI:CO KILDARE:County Kildare|\
EI:CO KILKENNY:County Kilkenny|\
EI:CO LAOIS:County Laois|\
EI:CO LONGFORD:County Longford|\
EI:CO LOUTH:County Louth|\
EI:CO MEATH:County Meath|\
EI:CO OFFALY:County Offaly|\
EI:CO WESTMEATH:County Westmeath|\
EI:CO WEXFORD:County Wexford|\
EI:CO WICKLOW:County Wicklow|\
EI:CO GALWAY:County Galway|\
EI:CO MAYO:County Mayo|\
EI:CO LEITRIM:County Leitrim|\
EI:CO ROSCOMMON:County Roscommon|\
EI:CO SLIGO:County Sligo|\
EI:CO CLARE:County Clare|\
EI:CO CORK:County Cork|\
EI:CO KERRY:County Kerry|\
EI:CO LIMERICK:County Limerick|\
EI:CO TIPPERARY:County Tipperary|\
EI:CO WATERFORD:County Waterford|\
';

// Country data table
//
// To edit the list, just delete a line or add a line. Order is important.
// The order displayed here is the order it appears on the drop down.
//
var country = '\
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|\
AP:Azores|\
BS:Bahamas|\
BH:Bahrain|\
BD:Bangladesh|\
BB:Barbados|\
BY:Belarus|\
BE:Belgium|\
BZ:Belize|\
BJ:Benin|\
BM:Bermuda|\
BT:Bhutan|\
BO:Bolivia|\
BA:Bosnia And Herzegowina|\
XB:Bosnia-Herzegovina|\
BW:Botswana|\
BV:Bouvet Island|\
BR:Brazil|\
IO:British Indian Ocean Territory|\
VG:British Virgin Islands|\
BN:Brunei Darussalam|\
BG:Bulgaria|\
BF:Burkina Faso|\
BI:Burundi|\
KH:Cambodia|\
CM:Cameroon|\
CA:Canada|\
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|\
CD:Congo, The Democratic Republic O|\
CK:Cook Islands|\
XE:Corsica|\
CR:Costa Rica|\
CI:Cote d` Ivoire (Ivory Coast)|\
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|\
ER:Eritrea|\
EE:Estonia|\
ET:Ethiopia|\
FK:Falkland Islands (Malvinas)|\
FO:Faroe Islands|\
FJ:Fiji|\
FI:Finland|\
FR:France (Includes Monaco)|\
FX:France, Metropolitan|\
GF:French Guiana|\
PF:French Polynesia|\
TA:French Polynesia (Tahiti)|\
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|\
GN:Guinea|\
GW:Guinea-Bissau|\
GY:Guyana|\
HT:Haiti|\
HM:Heard And Mc Donald Islands|\
VA:Holy See (Vatican City State)|\
HN:Honduras|\
HK:Hong Kong|\
HU:Hungary|\
IS:Iceland|\
IN:India|\
ID:Indonesia|\
IR:Iran|\
IQ:Iraq|\
IE:Ireland|\
EI:Ireland (Eire)|\
IL:Israel|\
IT:Italy|\
JM:Jamaica|\
JP:Japan|\
JO:Jordan|\
KZ:Kazakhstan|\
KE:Kenya|\
KI:Kiribati|\
KP:Korea, Democratic People\'S Repub|\
KW:Kuwait|\
KG:Kyrgyzstan|\
LA:Laos|\
LV:Latvia|\
LB:Lebanon|\
LS:Lesotho|\
LR:Liberia|\
LY:Libya|\
LI:Liechtenstein|\
LT:Lithuania|\
LU:Luxembourg|\
MO:Macao|\
MK:Macedonia|\
MG:Madagascar|\
ME:Madeira Islands|\
MW:Malawi|\
MY:Malaysia|\
MV:Maldives|\
ML:Mali|\
MT:Malta|\
MH:Marshall Islands|\
MQ:Martinique|\
MR:Mauritania|\
MU:Mauritius|\
YT:Mayotte|\
MX:Mexico|\
FM:Micronesia, Federated States Of|\
MD:Moldova, Republic Of|\
MC:Monaco|\
MN:Mongolia|\
MS:Montserrat|\
MA:Morocco|\
MZ:Mozambique|\
MM:Myanmar (Burma)|\
NA:Namibia|\
NR:Nauru|\
NP:Nepal|\
NL:Netherlands|\
AN:Netherlands Antilles|\
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|\
PS:Palestinian Territory, Occupied|\
PA:Panama|\
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|\
SM:San Marino|\
ST:Sao Tome and Principe|\
SA:Saudi Arabia|\
SN:Senegal|\
XS:Serbia-Montenegro|\
SC:Seychelles|\
SL:Sierra Leone|\
SG:Singapore|\
SK:Slovak Republic|\
SI:Slovenia|\
SB:Solomon Islands|\
SO:Somalia|\
ZA:South Africa|\
GS:South Georgia And The South Sand|\
KR:South Korea|\
ES:Spain|\
LK:Sri Lanka|\
NV:St. Christopher and Nevis|\
SH:St. Helena|\
LC:St. Lucia|\
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|\
TH:Thailand|\
TG:Togo|\
TK:Tokelau|\
TO:Tonga|\
TT:Trinidad and Tobago|\
XU:Tristan da Cunha|\
TN:Tunisia|\
TR:Turkey|\
TM:Turkmenistan|\
TC:Turks and Caicos Islands|\
TV:Tuvalu|\
UA:Ukraine|\
AE:United Arab Emirates|\
UK:United Kingdom|\
GB:Great Britain|\
US:United States|\
UG:Uganda|\
UM:United States Minor Outlying Isl|\
UY:Uruguay|\
UZ:Uzbekistan|\
VU:Vanuatu|\
XV:Vatican City|\
VE:Venezuela|\
VN:Vietnam|\
VI:Virgin Islands (U.S.)|\
WF:Wallis and Furuna Islands|\
EH:Western Sahara|\
WS:Western Samoa|\
YE:Yemen|\
YU:Yugoslavia|\
ZR:Zaire|\
ZM:Zambia|\
ZW:Zimbabwe|\
';

function TrimString(sInString) {
  if ( sInString ) {
    sInString = sInString.replace( /^\s+/g, "" );// strip leading
    return sInString.replace( /\s+$/g, "" );// strip trailing
  }
}

// Populates the country selected with the counties from the country list
function populateCountry(defaultCountry) {
  if ( postCountry != '' ) {
    defaultCountry = postCountry;
  }
  var countryLineArray = country.split('|');  // Split into lines
  var selObj = document.getElementById('countrySelect');
  selObj.options[0] = new Option('Select Country','');
  selObj.selectedIndex = 0;
  for (var loop = 0; loop < countryLineArray.length; loop++) {
    lineArray = countryLineArray[loop].split(':');
    countryCode  = TrimString(lineArray[0]);
    countryName  = TrimString(lineArray[1]);
    if ( countryCode != '' ) {
      selObj.options[loop + 1] = new Option(countryName, countryCode);
    }
    if ( defaultCountry == countryCode ) {
      selObj.selectedIndex = loop + 1;
    }
  }
}

function populateState() {
  var selObj = document.getElementById('stateSelect');
  var foundState = false;
  // Empty options just in case new drop down is shorter
  if ( selObj.type == 'select-one' ) {
    for (var i = 0; i < selObj.options.length; i++) {
      selObj.options[i] = null;
    }
    selObj.options.length=null;
    selObj.options[0] = new Option('Select State','');
    selObj.selectedIndex = 0;
  }
  // Populate the drop down with states from the selected country
  var stateLineArray = state.split("|");  // Split into lines
  var optionCntr = 1;
  for (var loop = 0; loop < stateLineArray.length; loop++) {
    lineArray = stateLineArray[loop].split(":");
    countryCode  = TrimString(lineArray[0]);
    stateCode    = TrimString(lineArray[1]);
    stateName    = TrimString(lineArray[2]);
  if (document.getElementById('countrySelect').value == countryCode && countryCode != '' ) {
    // If it's a input element, change it to a select
      if ( selObj.type == 'text' ) {
        parentObj = document.getElementById('stateSelect').parentNode;
        parentObj.removeChild(selObj);
        var inputSel = document.createElement("SELECT");
        inputSel.setAttribute("name","state");
        inputSel.setAttribute("id","stateSelect");
        parentObj.appendChild(inputSel) ;
        selObj = document.getElementById('stateSelect');
        selObj.options[0] = new Option('Select State','');
        selObj.selectedIndex = 0;
      }
      if ( stateCode != '' ) {
        selObj.options[optionCntr] = new Option(stateName, stateCode);
      }
      // See if it's selected from a previous post
      if ( stateCode == postState && countryCode == postCountry ) {
        selObj.selectedIndex = optionCntr;
      }
      foundState = true;
      optionCntr++
    }
  }
  // If the country has no states, change the select to a text box
  if ( ! foundState ) {
    parentObj = document.getElementById('stateSelect').parentNode;
    parentObj.removeChild(selObj);
  // Create the Input Field
    var inputEl = document.createElement("INPUT");
    inputEl.setAttribute("id", "stateSelect");
    inputEl.setAttribute("type", "text");
    inputEl.setAttribute("name", "state");
    inputEl.setAttribute("size", 20);
    inputEl.setAttribute("value", postState);
    parentObj.appendChild(inputEl) ;
  }
}

function initCountry(country) {
  populateCountry(country);
  populateState();
}


function setTxnIDFromPaymentType() {
	// pick the value on the payment type drop down
	paymentType = document.getElementById("paymenttype");
	paymentTypeValue = paymentType.options[paymentType.selectedIndex].value
	// set the value of the txn_id hidden field
	document.getElementById("txn_id").value = paymentTypeValue;  
	return; 	
}

function computeTotalPriceForProducts() {
	total = 0;
	if (document.getElementById('quantity').value == "") {
		document.getElementById('quantity').value = 1;
		computeTotalPriceForProducts();
	} else {
		quantity = new Number(document.getElementById('quantity').value);
		total = quantity * 30;
		document.getElementById('total_amount_display').innerHTML = formatAmount(total,2,'','.','','','-','');
	} 
}

function computeTotalPriceForDVDPack() {
	total = 0;
	if (document.getElementById('dvdquantity').value == "") {
		document.getElementById('dvdquantity').value = 1;
		country.options[country.selectedIndex].value = "US";
		computeTotalPriceForDVDPack();
	} else {
		quantity = new Number(document.getElementById('dvdquantity').value);
		total = quantity * 25;
		
		country = document.getElementById("country");
		selectedCountry = country.options[country.selectedIndex].value
		//alert("Selected Country:  " + selectedCountry);
		if (selectedCountry == "") {
			//alert("Please select a Country");
		} else if (selectedCountry == "US") {
			shipping = (Math.ceil(quantity/3) * 4.95);
		} else if (selectedCountry == "CA" || selectedCountry == "MX") {
			shipping = (Math.ceil(quantity/3) * 11.95);
		} else {
			shipping = (Math.ceil(quantity/3) * 13.95);
		}
		//shipping = shipping.toFixed(2)
		//alert("The shipping cost is " + shipping);
	} 
	total = total + shipping;
	//alert("The total cost is " + total);
	document.getElementById('amount').value = total;
	document.getElementById('shipping_amount_display').innerHTML = formatAmount(shipping,2,'','.','','','-','');
	document.getElementById('dvd_total_amount_display').innerHTML = formatAmount(total,2,'','.','','','-','');
}

// thousand separtor for amount fields
function formatAmount(num,dec,thou,pnt,curr1,curr2,n1,n2) {
	var x = Math.round(num * Math.pow(10,dec));
	if (x >= 0) n1=n2='';
	var y = (''+Math.abs(x)).split('');
	var z = y.length - dec; 
	if (z<0) z--; 
	for(var i = z; i < 0; i++) 
	y.unshift('0'); 
	if (z<0) z = 1; 
	y.splice(z, 0, pnt); 
	if(y[0] == pnt) y.unshift('0'); 
	while (z > 3) {
		z-=3; 
		y.splice(z,0,thou);
	}
	var r = curr1+n1+y.join('')+n2+curr2;return r;
}

// function to obsfuscate email addresses from spammers
function contactUnobsfuscate() {
	
	// find all links in HTML
	var link = document.getElementsByTagName && document.getElementsByTagName("a");
	var contact, e;
	
	// examine all links
	for (e = 0; link && e < link.length; e++) {
	
		// does the link have use a class named "contact"
		if ((" "+link[e].className+" ").indexOf(" contact ") >= 0) {
		
			// get the obfuscated contact address
			contact = link[e].firstChild.nodeValue.toLowerCase() || "";
			
			// transform into real contact address
			contact = contact.replace(/dot/ig, ".");
			contact = contact.replace(/\(at\)/ig, "@");
			contact = contact.replace(/\s/g, "");
			
			// is contact valid?
			if (/^[^@]+@[a-z0-9]+([_\.\-]{0,1}[a-z0-9]+)*([\.]{1}[a-z0-9]+)+$/.test(contact)) {
			
				// change into a real mailto link
				link[e].href = "mailto:" + contact;
				link[e].firstChild.nodeValue = contact;
		
			}
		}
	}
}
window.onload = contactUnobsfuscate;

function onAfter() {
		 // do nothing
}
