/********************************************************************************
*      Script: mdscicdonations.js
* Description: Routines used to process patch donation orders
*    Comments: Intellectual property of Clint Collier on loan to MDSC-IC for non-commercial use
					on this web site only.  These routines may not be given to others or used in 
*					any other way without the express consent of the author.
*     Created: 03/24/2005 [CLC]
*    Modified:
*********************************************************************************/

function valid_email(email_address) {
    if (email_address.length < 5) {
        return false
    }
    at_location = email_address.indexOf("@")
    dot_location = email_address.lastIndexOf(".")
    if (at_location == -1 || dot_location == -1 || at_location > dot_location ) {
        return false
    }
    if (at_location == 0) {
        return false
    }
    if (dot_location - at_location < 2 ) {
        return false
    }
    if (email_address.length - dot_location < 2) {
        return false
    }
    return true
} // valid_email


function valid_shipping(order_form) {
	with (order_form) {
		if (first_name.value.length <=2) {
			first_name.focus()
			alert("First Name must be at least 2 characters")
			return false
		}
		if (last_name.value.length <=2) {
			last_name.focus()
			alert("Last Name must be at least 2 characters")
			return false
		}
		if (address_street.value.length <=5) {
			address_street.focus()
			alert("Address must be at least 5 characters")
			return false
		}
		if (address_city.value.length <=5) {
			address_city.focus()
			alert("City must be at least 5 characters")
			return false
		}
		if (address_state.value.length != 2) {
			address_state.focus()
			alert("State abbreviation must be 2 characters" + address_state.value.length)
			return false
		}
		if (zip1.value.length !=5) {
			zip1.focus()
			alert("ZIP code must be 5 characters")
			return false
		}
		/* we dont collect phone number
		if ((phoneareacd.value.length != 3) || (phonenpa.value.length != 3) || (phoneno.value.length != 4)) {
			phoneareacd.focus()
			alert("The phone number does not appear valid")
			return false
		}
		*/
		if (valid_email(payer_email.value) != true) {
			payer_email.focus()
			alert("The e-mail address does not appear valid")
			return false
		}
	}
	return true
} //verify_shipping


function time_stamp(date) {
	var month = new Array(12)
		month[0] = "Jan"
		month[1] = "Feb"
		month[2] = "Mar"
		month[3] = "Apr"
		month[4] = "May"
		month[5] = "Jun"
		month[6] = "Jul"
		month[7] = "Aug"
		month[8] = "Sep"
		month[9] = "Oct"
		month[10] = "Nov"
		month[11] = "Dec"
	var dow = new Array(7)
		dow[0] = "Sunday"
		dow[1] = "Monday"
		dow[2] = "Tuesday"
		dow[3] = "Wednesday"
		dow[4] = "Thursday"
		dow[5] = "Friday"
		dow[6] = "Saturday"
	var hours = date.getHours()
	var minutes = date.getMinutes()
	var seconds = date.getSeconds()
	if (hours <= 9) {hours = "0" + hours}
	if (minutes <= 9) {minutes = "0" + minutes}
	if (seconds <= 9) {seconds = "0" + seconds}
	var timestamp
	timestamp = hours + ":" + minutes + ":" + seconds + " on " + month[date.getMonth()] + " " + date.getDate() + ", " + (date.getYear()+1900)
return timestamp
} //time_stamp


function calculate_line(field1, price1, field2, price2, field3, price3, field4, price4) {
	/* 
	The function calculate_line receives the values from the first three input variables from a table line along with the set price for that cell.
	*/
	var line_cost = 0
	if(isNaN(field1)) {field1 = parseInt("0")}
	if(isNaN(field2)) {field2 = parseInt("0")}
	if(isNaN(field3)) {field3 = parseInt("0")}
	if(isNaN(field4)) {field4 = parseInt("0")}
	line_count = field1 + field2 + field3 + field4
	if(isNaN(line_count)) {line_count = parseInt("0")}
	total_count = total_count + line_count
	line_cost = ((field1 * price1) + (field2 * price2) + (field3 * price3) + (field4 * price4))
	total_cost = total_cost + line_cost
	if (line_cost == 0) {
		if (line_count > 0) {
			display_line_cost = "$0.00"
		}
		else {
			display_line_cost = " "
		}
	}
	else {
		display_line_cost = " $" + line_cost + ".00"
	}
} //calculate_line


function do_print(order_form, program, pgm_no, unit_price) {
	verify_form(order_form, program, pgm_no, unit_price)
	// print()
	if (!verify_form(order_form,program,pgm_no,unit_price)) return false;
	order_form.action = "../scripts/printdonationform.php";
	order_form.submit()
	return true
} // do_print


function round_decimals(original_number, decimals) {
    var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    return pad_with_zeros(result3, decimals)
} //round_decimals


function pad_with_zeros(rounded_value, decimal_places) {
    // Convert the number to a string
    var value_string = rounded_value.toString()
    // Locate the decimal point
    var decimal_location = value_string.indexOf(".")
    // Is there a decimal point?
    if (decimal_location == -1) {
        // If no, then all decimal places will be padded with 0s
        decimal_part_length = 0
       // If decimal_places is greater than zero, tack on a decimal point
        value_string += decimal_places > 0 ? "." : ""
    }
    else {
        // If yes, then only the extra decimal places will be padded with 0s
        decimal_part_length = value_string.length - decimal_location - 1
    }
    // Calculate the number of decimal places that need to be padded with 0s
    var pad_total = decimal_places - decimal_part_length
    if (pad_total > 0) {
        // Pad the string with 0s
        for (var counter = 1; counter <= pad_total; counter++) 
            value_string += "0"
        }
    return value_string
} //pad_with_zeros


function ck_full(this_field,length,next_field) {
	if (this_field.value.length == length) {next_field.focus()}
} //ck_full


function format_dollars(display_field, display_length){
	if (display_field.length < display_length) {
		for (var counter = display_field.length; counter <= display_length; counter++)
			display_field = " " + display_field
	}
	display_field = " $" + display_field
	return display_field
} //format_dollars

function deflect_focus(current_field) {
	var current_form = current_field.form
	var total_fields = current_form.elements.length
	
	// is there another field?
	if (total_fields > 1) {
		for (counter = 0; counter < total_fields; counter ++) {
			if (current_field.name == current_form.elements[counter].name) {
				var current_index = counter
				break
			}
		}
		//is this the first field?
		if (current_index == 0) {
			current_form.elements[1].focus() // set the foucus on the second field
		}
		else {
			for (counter = (current_index +1); counter < total_fields; counter ++) {
				if (current_form.elements[counter].type != "hidden") {	
					current_form.elements[counter].focus()
					break
				}
			}
		}
	}
} // delfec_focus


function openWindow(url,w,h) {
Version=navigator.appVersion;
var showpic=null;
w=w+20;
h=h+30;
showpic = window.open(url,"Image",'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=no,resizable=0,'+'width='+w+',height='+h);
        if ((Version.substring(0,1)>= 3) && (Version.indexOf("MSIE") == -1)) {
        showpic.focus();
        }
} // openWindow


// Code that does the actual form population/calculation of price
var patch_price = 0
var minimum_cost = 0
var trans_fee = 0.30  // this is the paypal per transaction fee
var trans_pct = 0.029 // this is what paypal charges us
var postage_base = 0.55
var postage_unit = 8
var postage_cost = 0
var handling_fee = 0
var grand_total = 0

function RJust(field,desired_length) {
	pad = false
	if (field.length != desired_length) {pad = true}
	while (field.length < desired_length) {
		field = " " + field
	}
	if (pad) {field = " " + field}
	return field
}  // RJust

function add_fields(order_form, program, pgm_no, unit_price) {
	var display_cost = " "
	patch_price = parseFloat(unit_price)
	with (order_form) {
		order_form.os0.value = ""
		order_form.os1.value = ""
		if (isNaN(patch_qty.value) | (patch_qty.value < 1)) {
			alert("You must enter a number of patches desired")
			patch_cost.value = ""
			handling.value = ""
			total_cost.value = ""
			return
		}
	
		postage_cost = (parseInt(patch_qty.value / postage_unit) * postage_base)
		if (postage_cost == 0) {postage_cost = postage_base}
	
		minimum_cost = parseInt(patch_qty.value) * patch_price
		// Check to see if the user entered a dollar value greater than the minimum....
		if (patch_cost.value > minimum_cost) {
			minimum_cost = parseFloat(patch_cost.value)
		}
		handling_fee = ((parseInt(patch_qty.value) * patch_price) * trans_pct) + trans_fee + postage_cost
		

		grand_total = minimum_cost + handling_fee + postage_cost
	
		display_cost = round_decimals(minimum_cost,2)
		patch_cost.value = display_cost
	
		display_cost = round_decimals(handling_fee,2)
		handling.value = RJust(display_cost,patch_cost.value.length)
	
		grand_total = parseFloat(patch_cost.value) + parseFloat(handling.value)
		display_cost = round_decimals(grand_total,2)
		total_cost.value = display_cost
		
	} // with...
} // add_fields
	
  
function verify_form(order_form, program, pgm_no, unit_price) {
	add_fields(order_form, program, pgm_no, unit_price) 
	if(valid_shipping(order_form) != true){return false}
	with (order_form) {
		// Populate our PayPal fields here!
		switch(pgm_no) {
			case 1 : item_name.value = "WFF Donation"; break
			case 2 : item_name.value = "JOTI Purchase"; break
			case 3 : item_name.value = "JOTA Purchase"; break
			case 4 : item_name.value = "Tsunami Donation"; break
			default: item_name.value = "Unknown transaction"
		}		
		item_number.value = pgm_no				// for our intformation on which patch was ordered
		amount.value = patch_cost.value 		// this is the amount paypal will add postage to and bill
		switch(pgm_no) {
			case 1  : qnty_field = patch_qty.value + ";0;0;0;"; break
			case 2  : qnty_field = "0;" + patch_qty.value + ";0;0;"; break
			case 3  : qnty_field = "0;0;" + patch_qty.value + ";0;"; break
			case 4  : qnty_field = "0;0;0;" + patch_qty.value + ";"; break
			default : qnty_field = patch_qty.value + ";0;0;0;"
		}
		
		os0.value = program + ": " + patch_qty.value + " patches @ $" + unit_price + "/each  Total donation: " + patch_cost.value + "  Handling: " + handling.value + "  Total order: " + total_cost.value + " - " + time_stamp(new Date())
		
		os1.value = first_name.value + ";" + last_name.value + ";" + address_street.value + ";" + address_city.value + ";" + address_state.value + ";" + zip1.value + zip2.value + ";" + address_country.value + ";" + unit.value + ";" + payer_email.value + ";" + qnty_field + patch_cost.value + ";" + handling.value + ";Online;" + comments.value
		
		if (zip2.value == " ") {
			address_zip.value = zip1.value
		}
		else {
			address_zip.value = zip1.value + "-" + zip2.value	 
		}
		
	} //with (order_form)
	return true
} //verify_form


function getFullName(program) {
	switch (program) {
			case "WFF"  : program_name="World Friendship Fund"; break
			case "JOTI" : program_name="Jambore on the Internet"; break
			case "JOTA" : program_name="Jamoboree on the Air"; break
			case "Tsu"  : program_name="Tsunami Scout Relief"; break
			default     : program_name="Mt. Diablo Silverado International Committee"
	}
} //getFullName

