function change_type() {
	
	//get the selected type
	for (var i=0; i<document.forms['subscribe_form'].elements['type'].length; i++) {
		if (document.forms['subscribe_form'].elements['type'][i].checked) {
			var set_value = document.forms['subscribe_form'].elements['type'][i].value;
		}
	}
	
	update_total();
}
function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

//we need to keep track if they aer resubscribing, 
var resubscription = false;
//this array will keep track of the items that the user has selected, and their codes,
//here is the master list

// insights_jbms = 100				
// insights_review = 200
// insights_studies = 105
// insights_review_studies_jbms = 104
// insights_review_studies = 103
// insights_jbms_studies = 102
// insights_jbms_review = 101
// review = 200
// Silver = 300
// Gold = 400
// Liahona = 500
// Donate = 600

//here lies the OLD! master list
// insights_jbms = 100
// insights_jbms + review = 101
//review = 200
//Silver = 300
//Gold = 400
//Liahona = 500
//Donate = 600




/*	
	None	
	JBMS + Insights	$25
	FARMS Review + Insights	$20
	Studies + Insights	$15
	JBMS + FARMS Review + Insights	$55
	JBMS + Studies + Insights	$42
	Farms Review + Studies + Insights	$42
	JBMS + Farms Review + Studies + Insights	$65
	Silver	$120
	Gold	$500
	Liahona	$1,000
*/







item_code = new Array();

item_code[1] = new Array();
item_code[2] = new Array();
item_code[3] = new Array();

//keep track of how many items we have
var item_count = 1;

function update_total() {
	var new_total = 0;
	//rest the item count so that it will overwrite old values
	item_code[1] = new Array();
	item_code[2] = new Array();
	item_code[3] = new Array();
	item_count = 1;
	//see which boxes are checked
	for (var i=0; i<document.forms['subscribe_form'].elements['type'].length; i++) {
		if (document.forms['subscribe_form'].elements['type'][i].checked) {
			if (document.forms['subscribe_form'].elements['type'][i].value == 'insights_jbms') {
				new_total += 30;
				
					item_code[item_count]['code'] = 100;
					item_code[item_count]['amount'] = 30;
					item_count++;
			}			
//////////////////////////////////////////////	added 1-5-10 ///////////////////////////////////////////////////////////////////


			if (document.forms['subscribe_form'].elements['type'][i].value == 'insights_jbms_review') {
				new_total += 55;
				
					item_code[item_count]['code'] = 101;
					item_code[item_count]['amount'] = 55;
					item_count++;
			}
			

			if (document.forms['subscribe_form'].elements['type'][i].value == 'insights_jbms_studies') {
				new_total += 42;
				
					item_code[item_count]['code'] = 102;
					item_code[item_count]['amount'] = 42;
					item_count++;
			}			
			

			if (document.forms['subscribe_form'].elements['type'][i].value == 'insights_review_studies') {
				new_total += 42;
				
					item_code[item_count]['code'] = 103;
					item_code[item_count]['amount'] = 42;
					item_count++;
			}	
			

			if (document.forms['subscribe_form'].elements['type'][i].value == 'insights_review_studies_jbms') {
				new_total += 65;
				
					item_code[item_count]['code'] = 104;
					item_code[item_count]['amount'] = 65;
					item_count++;
			}
			

			if (document.forms['subscribe_form'].elements['type'][i].value == 'insights_studies') {
				new_total += 15;
				
					item_code[item_count]['code'] = 105;
					item_code[item_count]['amount'] = 15;
					item_count++;
			}			
			
///////////////////////////////////////////////////end of added 1-5-10///////////////////////////////////////////////////////////

			if (document.forms['subscribe_form'].elements['type'][i].value == 'review') {
				new_total += 30;
				item_code[item_count]['code'] = 200;
				item_code[item_count]['amount'] = 30;

				item_count++;
			}
			if (document.forms['subscribe_form'].elements['type'][i].value == 'silver') {
				new_total += 120;
				item_code[item_count]['code'] = 300;
				item_code[item_count]['amount'] = 120;
				item_count++;
			}
			if (document.forms['subscribe_form'].elements['type'][i].value == 'gold') {
				new_total += 500;
				item_code[item_count]['code'] = 400;
				item_code[item_count]['amount'] = 500;

				item_count++;
			}
			if (document.forms['subscribe_form'].elements['type'][i].value == 'liahona') {
				new_total += 1000;
				item_code[item_count]['code'] = 500;
				item_code[item_count]['amount'] = 1000;

				item_count++;
			}
		}
	}
	//see if the donate box is checked, if it is add its value
	if (document.getElementById("donate_checkbox").checked) {
		
		//make sure the value in the textbox is only numbers, if it is not then blank it
		if (document.getElementById("donate_field").value * 1) {
			new_total = new_total+(document.getElementById("donate_field").value * 1);
			item_code[item_count]['code'] = 600;
			item_code[item_count]['amount'] = document.getElementById("donate_field").value * 1;
			
			item_count++;
		}
		
	}
	
	
	document.getElementById("items_total").innerHTML = "$"+addCommas(new_total);
	//alert(item_code[1]['code']+', '+item_code[2]['code']+', '+item_code[3]['code']);
	return new_total;
	
}
function subscribe_login_wrapper() {
	document.getElementById("login_results").innerHTML = '<i>Working.....</i>';
	jQuery("#login_results").slideDown("slow");
	xajax_subscribe_login(document.getElementById("login_customer_id").value, document.getElementById("login_emailorphone").value);
}
function update_order() {

			//call the xajax update function to update the customers information
			jQuery("#update_msg").slideUp("slow");
			xajax.call( 'subscribe_update', { mode:'synchronous', parameters:[						
						document.getElementById('login_customer_id').value,		
						document.getElementById('first_name').value,		
						document.getElementById('last_name').value,
						document.getElementById('address1').value,
						document.getElementById('address2').value,
						document.getElementById('city').value,
						document.getElementById('state').value,
						document.getElementById('zip').value,
						document.getElementById('country').value,
						document.getElementById('billingfirst_name').value,
						document.getElementById('billinglast_name').value,
						document.getElementById('billingaddress1').value,
						document.getElementById('billingaddress2').value,
						document.getElementById('billingcity').value,
						document.getElementById('billingstate').value,
						document.getElementById('billingzip').value,
						document.getElementById('billingcountry').value,
						document.getElementById('billingphone').value,
						document.getElementById('billingemail').value,
						document.getElementById('phone').value,
						document.getElementById('phone2').value,
						document.getElementById('fax').value,
						document.getElementById('email').value
						] } );
			//inform the user that their information has been updated
			document.getElementById("update_msg").innerHTML = '<span style="font-weight:bold;font-size:1.4em;color: green;">Your contact information has been updated.</span>';
			jQuery("#update_msg").slideDown("slow");

			
			//alert('does this work');
}
function verify_order() {
	//this function verifies the order, and then if its ready, prints out an order summary that allows it to be submitted
	//start the error msg varible, this will be written to when we need it
	var error_msg = '';
	
	//make sure they have have selected something to buy
	var buying = false;
	for (var i=0; i<document.forms['subscribe_form'].elements['type'].length; i++) {
		if (document.forms['subscribe_form'].elements['type'][i].checked) {
			if (document.forms['subscribe_form'].elements['type'][i].value != 'none') {
				buying = true;
			}
		}
	}

	if (document.getElementById("review_checkbox").checked) {
		buying = true;
	}

	if (document.getElementById("donate_checkbox").checked) {
		//make sure the value in the textbox is only numbers, if it is not then blank it
		if (document.getElementById("donate_field").value * 1) {
			buying = true;
		}
	}
	
	if (!buying) {
		error_msg += "Please select something to purchase<br>";
	}
	
	//check to make sure the form is filled out
	var field_id = new Array();
	var field_regex = new Array();
	var field_name = new Array();

	field_id[1] = 'first_name';
	field_name[1] = 'First Name';
	field_regex[1] = /^[^']+$/i;
	
	field_id[2] = 'last_name';
	field_name[2] = 'Last Name';
	field_regex[2] = /^[^']+$/i;

	field_id[3] = 'address1';
	field_name[3] = 'Address 1';
	field_regex[3] = /^[^']+$/i;
	
	field_id[4] = 'city';
	field_name[4] = 'City';
	field_regex[4] = /^[^']+$/i;

	field_id[5] = 'state';
	field_name[5] = 'State';
	field_regex[5] = /^[^']+$/i;

	field_id[6] = 'zip';
	field_name[6] = 'Zip';
	field_regex[6] = /^[^']+$/i;

	field_id[7] = 'country';
	field_name[7] = 'Country';
	field_regex[7] = /^[^']+$/i;

	field_id[8] = 'phone';
	field_name[8] = 'Phone';
	field_regex[8] = /^[0-9\-\s\,\.\(\)]+$/i;

	field_id[9] = 'email';
	field_name[9] = 'Email';
	field_regex[9] = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
	
	//cycle through the fields and check them
	for (i=1;i<=9;i++) {
		//trim leading and tailing spaces
		document.getElementById(field_id[i]).value = trim(document.getElementById(field_id[i]).value);
		if (!document.getElementById(field_id[i]).value.match(field_regex[i])) {
			error_msg += "The <b>"+field_name[i]+"</b> field was not filled in correctly, to continute with your subscription, please correct it<br>";
			document.getElementById(field_id[i]).style.backgroundColor = '#FFD4D4';
		} else {
			document.getElementById(field_id[i]).style.backgroundColor = '';
		}
		//todo check seperarte adresses
	}
	
	//write the error
	if (error_msg != '') {
		document.getElementById("error_msg").innerHTML = 'Please correct these items to procede with your subscription<br>&nbsp;<br><i>'+error_msg+'</i>';
		jQuery("#error_msg").slideDown("slow");
		document.getElementById("verify_button").style.display = '';
		document.getElementById("process_button").style.display = 'none';
		return false;
	} else {
		//only animate this if it is not currently being displayed
		jQuery("#error_msg").slideUp("slow");
		
		//make the verify button invisible
		document.getElementById("verify_button").style.display = 'none';
		//and make the process button visible
		document.getElementById("process_button").style.display = '';
		document.getElementById("error_msg").innerHTML = '<span style="color: green;">Your Information has been verified, Your order is ready to be processed</span>';
		jQuery("#error_msg").slideDown("slow");

		return true;

	}
}
function process_order() {
	//recheck the form to make sure that it is good
	if (verify_order()) {
		
		//add the user the database, if they are new, and if they are returning, then update their entry int he dbase
		if (!resubscription) {
			//call the function snycronously so we can get a return calue
			
			var new_customer_id = xajax.call( 'subscribe_new', { mode:'synchronous', parameters:[						
						document.getElementById('first_name').value,		
						document.getElementById('last_name').value,
						document.getElementById('address1').value,
						document.getElementById('address2').value,
						document.getElementById('city').value,
						document.getElementById('state').value,
						document.getElementById('zip').value,
						document.getElementById('country').value,
						document.getElementById('billingfirst_name').value,
						document.getElementById('billinglast_name').value,
						document.getElementById('billingaddress1').value,
						document.getElementById('billingaddress2').value,
						document.getElementById('billingcity').value,
						document.getElementById('billingstate').value,
						document.getElementById('billingzip').value,
						document.getElementById('billingcountry').value,
						document.getElementById('billingphone').value,
						document.getElementById('billingemail').value,
						document.getElementById('phone').value,
						document.getElementById('phone2').value,
						document.getElementById('fax').value,
						document.getElementById('email').value
						] } );

		} else {
			//update functionality
			update_order();                    
			var new_customer_id = document.getElementById('login_customer_id').value
		}
		
		//build the form we will submit to cashnet
		var form_div_html = '';
		form_div_html += '</form>';
		
		form_div_html += '<form name="entryform" action="https://commerce.cashnet.com/WEBNMAX" method="post">';

			//build an array with all the hidden varables and their names and values
			fields = new Array();
			for (var x = 1 ; x <= 10 ; x++) {
				fields[x] = new Array();
			}
			
			fields[1]['name'] = 'itemcode';
			fields[1]['value'] = '7251';
			
			fields[2]['name'] = 'amount';
			fields[2]['value'] = update_total();
			
			//this information will be sent to cashnet, they want the billing information, if it is different
			if (
				document.getElementById('billingaddress1').value != ''
				&& document.getElementById('billingcity').value != ''
				&& document.getElementById('billingstate').value != ''
				&& document.getElementById('billingzip').value != ''
				) {
					fields[3]['name'] = 'addr';
					fields[3]['value'] = document.getElementById('billingaddress1').value;
			
					fields[4]['name'] = 'city';
					fields[4]['value'] = document.getElementById('billingcity').value;
					
					fields[5]['name'] = 'state';
					fields[5]['value'] = document.getElementById('billingstate').value;
					
					fields[6]['name'] = 'zip';
					fields[6]['value'] = document.getElementById('billingzip').value;
				} else {
					fields[3]['name'] = 'addr';
					fields[3]['value'] = document.getElementById('address1').value;
			
					fields[4]['name'] = 'city';
					fields[4]['value'] = document.getElementById('city').value;
					
					fields[5]['name'] = 'state';
					fields[5]['value'] = document.getElementById('state').value;
					
					fields[6]['name'] = 'zip';
					fields[6]['value'] = document.getElementById('zip').value;
				}
			
			for (var i = 1 ; i <= 6 ; i++) {
				form_div_html += '<INPUT TYPE="hidden" NAME="'+fields[i]['name']+'" value="'+fields[i]['value']+'" />';
			}
	
			//variables that we want returned to us
			//amount
			
			
			//it has a problem with true/false, but thats ok as it is just translated into 1 or 0 later anyway, lets just do it now
			if (resubscription) {
					var resubscription_bin = 1;
			} else {
					var resubscription_bin = 0;
			}
			//this function will set a variable called transaction_id
			//call this function syncronously
			transaction_id = xajax.call( 'subscribe_new_transaction', { mode:'synchronous', parameters:[
																											new_customer_id,
																											item_code[1]['code'],
																											item_code[1]['amount'],
																											item_code[2]['code'],
																											item_code[2]['amount'],
																											item_code[3]['code'],
																											item_code[3]['amount'],
																											update_total(),
																											resubscription_bin
																										] } );
			
			form_div_html += '<input type="hidden" name="REF1TYPE1" value="billtoname" />';
			form_div_html += '<input type="hidden" name="REF1VAL1" value="'+transaction_id+'">';
			
			//becouse we can only pass one value to cashnet that it will pass back, we are going to create a transaction ID, this will help us out alot, 
			//becouse it will store teh data that we need and then we can just turn around and pull it back out when we finish up

		form_div_html += '</form>';
		//place the form on the page
		document.getElementById("submit_form_div").innerHTML = form_div_html;
		//submit the form that we just built
		//only submit the form that we just built if the data in it has been successfuly recorded in the database
		//this means taht the data was successfuly returned
		if (typeof(new_customer_id) !== 'undefined' && typeof(transaction_id) !== 'undefined') {
			document.forms['entryform'].submit();
		} else {
			alert("There seems to be a problem recording your purchase in our database, please call 1-800-327-6715 or email maxwell_institute@byu.edu and report it.");
		}
		
		
	}

}

// remove multiple, leading or trailing spaces
function trim(s) {
	s = s.replace(/(^\s*)|(\s*$)/gi,"");
	s = s.replace(/[ ]{2,}/gi," ");
	s = s.replace(/\n /,"\n");
	return s;
}

