/*
 * PURPOSE:      Sets a flag that indicates that user wants to print and mail their order, and submits the Checkout form
 * PARAMETERS:    N/A
 * RETURN VALUE:  N/A
 * REVISIONS:     09/2009 - created
 */
function print_and_mail() {
  var o_form

  o_form = document.forms.checkout
  if (!o_form) return

  o_form.payment_option.value = 1
	
	if (!validate_checkout()) return
	
	o_form.submit()
	
  return
}

/*
 * PURPOSE:      Sets a flag that indicates that user wants to pay their order online, and submits the Checkout form
 * PARAMETERS:    N/A
 * RETURN VALUE:  N/A
 * REVISIONS:     09/2009 - created
 */
function pay_online() {
  var o_form
	
  o_form = document.forms.checkout
  if (!o_form) return

  o_form.payment_option.value = ""
	
	if (!validate_checkout()) return
	
	o_form.submit()
	
  return
}

/*
 * PURPOSE:      Validates the Checkout form
 * PARAMETERS:    N/A
 * RETURN VALUE:  true - if all the fields contain acceptable values, and required fields are non-blank
 *                false - otherwise
 * REVISIONS:     09/2009 - created
 */
function validate_checkout(){
  // variables
  var fTotal
	var country
  // objects
  var o_form
  var o_elt	
	
	o_form = document.forms.checkout
	if (!o_form) return false
	
	if (!validate('checkout','firstname|lastname|address|city|zip|country|email','Please enter your first name.|Please enter your last name.|Please enter your street address.|Please enter your city.|Please enter your postal code.|Please select your country.|Please enter your email address.','||||3||1','||||Please enter a valid zip code.||Please enter a valid email address.',false)) return false

  o_country = o_form.country
	if (!o_country) {
		if (confirm("PayPal can only accept payments from certain countries.\nWe are unable to determine the country of your billing address and therefore cannot accept payment through PayPal.\nWould you like to automatically change the payment method to 'Print and Mail'?")) {
			o_form.printandmail.value = 1
		} else {
			return false
		}
		
	} else {
	  country = o_country.value
	  if ((country == "USA")  && (o_form.state.selectedIndex < 1)) {
		  alert("Please select your state.")
			set_focus("checkout", "state")
			return false
		}
	  if ((country == "Canada")  && (o_form.state.selectedIndex < 1)) {
		  alert("Please select your province.")
			set_focus("checkout", "state")
			return false
		}
		
	  if ((!allows_pay_pal(country)) && (oForm.printandmail.value == "")) {
	    if (confirm("You cannot pay with PayPal from " + country + ". Would you like to automatically change the payment method to 'Print and Mail'?")) {
		    oForm.printandmail.value = 1
		  } else {
        return false
      }
	  }
  }

	o_elt = o_form.total
	if (!o_elt) return false
	fTotal = parseFloatSafe(o_elt.value)   

	if (! (fTotal > 0) ) {
	  alert("The shopping cart is empty.")
    return false 
	}
	
	if (window.confirm("You are about to submit your order.\nOnce you submit the order, you cannot make any changes to it.\nWould you like to continue?")) {

	if ((o_form.s_firstname.value != o_form.firstname.value) || (o_form.s_lastname.value != o_form.lastname.value) || (o_form.s_address.value != o_form.address.value) || (o_form.s_city.value != o_form.city.value) ||	(o_form.s_zip.value != o_form.zip.value) || (o_form.s_country.selectedIndex != o_form.country.selectedIndex) ||	(o_form.s_state.selectedIndex != o_form.state.selectedIndex) ||	(o_form.s_email.value != o_form.email.value) || (o_form.s_phone2.value != o_form.phone2.value)) {
	  o_elt = o_form.s_sameaddress
		if (o_elt) o_elt.checked = false
	}

	  return  true
	} else {
    return false
  }

	return true 
} 

/*
 * PURPOSE:      This function determines whether PayPal payments can be accepted from the specified country.
 * PARAMETERS:    country - name of the country
 * RETURN VALUE:  true - if PayPal can process payments in this country
 *                false - if not
 * REVISIONS:     09/2006 - created
 */
function allows_pay_pal(country) {
	 return (country == "USA") || (country == "Australia") || (country == "Austria") ||
 		     (country == "Beligum") || (country == "Canada") || (country == "China") || 
 		     (country == "France") || (country == "Germany") || (country == "Italy") || 
 		     (country == "Netherlands") || (country == "Spain") || (country == "Switzerland") || 
 		     (country == "United Kingdom") || (country == "Denmark") || (country == "Finland") ||
 		     (country == "Greece") || (country == "Hong Kong") || (country == "Ireland") || 
 		     (country == "Japan") || (country == "Mexico") || (country == "New Zealand") || 
 		     (country == "Norway") || (country == "Portugal") || (country == "Singapore") || 
 		     (country == "South Korea") || (country == "Sweden") || (country == "Taiwan") ||
 		     (country == "Argentina") || (country == "Brazil") || (country == "Chile") || 
 		     (country == "Ecuador") || (country == "India") || (country == "Jamaica") || 
 		     (country == "Uruguay") || (country == "Costa Rica") || (country == "Dominican Republic") ||
 		     (country == "Iceland") || (country == "Israel") || (country == "Malaysia") || 
 		     (country == "Thailand") || (country == "Turkey") || (country == "Venezuela")
}

/*
 * PURPOSE:      This function updates tax, shipping and order total. Called when the state or country of the
 *               billing address changed.
 * PARAMETERS:    target - URL of the page to submit to in order to update the $_SESSION variables
 * RETURN VALUE:  N/A
 * REVISIONS:     09/2006 - created
 */
function update_shipping_tax(target) {
  var o_tax
  var o_shipping
  var o_grand_total
	var total
	var total_quantity
	var one_per_box
	var total_unlimited
	var state
	var country
	var s_state
	var s_country
	var o_form
	var o_elt
	
  o_form = document.forms.checkout
	if (!o_form) return

	o_elt = o_form.total
	if (!o_elt) return
	total = o_elt.value

	o_elt = o_form.total_quantity
	if (!o_elt) return
	total_quantity = o_elt.value

	o_elt = o_form.cnt_one_per_box
	if (!o_elt) return
	one_per_box = o_elt.value

	o_elt = o_form.total_unlimited_per_box
	if (!o_elt) return
	total_unlimited = o_elt.value

	o_elt = o_form.state
	if (!o_elt) return
	if (o_elt.options.length < 1) { 
		state = ""
	} else {
		state = o_elt.options[o_elt.selectedIndex].value
	}
	
	o_elt = o_form.country
	if (!o_elt) return
	country = o_elt.options[o_elt.selectedIndex].value

	o_elt = o_form.s_state
	if (!o_elt) return
	if (o_elt.options.length < 1) { 
		s_state = ""
	} else {
		s_state = o_elt.options[o_elt.selectedIndex].value
	}
	
	o_elt = o_form.s_country
	if (!o_elt) return
	s_country = o_elt.options[o_elt.selectedIndex].value
	
	o_tax = document.getElementById("tdtax")
	if (!o_tax) return

	o_shipping = document.getElementById("tdshipping")
	if (!o_shipping) return
  
	o_grand_total = document.getElementById("tdtotal")
	if (!o_grand_total) return

	var handleSuccess = function(o){ 
	    var result_string = ""
      
	    if (o.responseText !== undefined) { 
				result_string = o.responseText.toString().replace(/\n/gi,'');
				// alert(result_string)
				result_arr = result_string.split(String.fromCharCode(1))
				if (parseInt(result_arr[0]) == 1) {
					o_tax.innerHTML = result_arr[4] + result_arr[1]
					o_shipping.innerHTML = result_arr[4] + result_arr[2]
					o_grand_total.innerHTML = result_arr[4] + result_arr[3]
					o_tax = o_form.tax
					if (o_tax) o_tax.value = result_arr[1]
					o_shipping = o_form.shipping
					if (o_shipping) o_shipping.value = result_arr[2]
				} else {
					alert("Could not update order total.")
				}
			} else {
				alert("Could not update order total.")	
			}
	} 
	
	var handleFailure = function(o) {
		alert("Could not update order total.")	
	}
	
	var callback = 
	{ 
	  success:handleSuccess, 
	  failure: handleFailure, 
	  argument: [] 
	}; 

	var post_data = "total=" + total + "&cnt_one_per_box= " + one_per_box + "&total_unlimited_per_box=" + total_unlimited + "&state=" + state + "&country=" + country + "&s_state=" + s_state + "&s_country=" + s_country
	var request = YAHOO.util.Connect.asyncRequest('POST', target, callback, post_data); 
}

/*
 * PURPOSE:       This function is called when user clicks "Return to Shopping Cart" button.
 *                Saves off the values that the user has already entered, so that when he/she returns to the Checkout page,
 *                he/she doesn't have to enter them again
 * PARAMETERS:    target  - URL to submit the form to to update the address values in the $_SESSION variable
 *                path - path where add_to_cart.php is located
 * RETURN VALUE:  N/A
 * REVISIONS:     09/2006 - created
 */
function go_back(target, path) {
  var o_form
	var oElt
	var params
	
	o_form = document.forms.checkout
	if (!o_form) {
		location.href = path + 'checkout/add_to_cart.php?action=view'	
	  return
	}

	var handleSuccess = function(o){ 
	    var result_string = ""

			/*			
	    if (o.responseText !== undefined) { 
				result_string = o.responseText.toString().replace(/\n/gi,'');
				alert(result_string)				
			}
			*/
			
			location.href = path + 'checkout/add_to_cart.php?action=view'				
	} 
	
	var handleFailure = function(o) {
		location.href = path + 'checkout/add_to_cart.php?action=view'	
	}
	
	var callback = 
	{ 
	  success:handleSuccess, 
	  failure: handleFailure, 
	  argument: [] 
	}; 

	YAHOO.util.Connect.setForm(o_form); 
	var request = YAHOO.util.Connect.asyncRequest('POST', target, callback, ""); 
}

/*
 * PURPOSE:       This function is called when user changes the State field on the checkout form
 * PARAMETERS:    state   - name of the field containing the states drop-down
 *                country - name of the field containing the countries drop-down
 * RETURN VALUE:  N/A
 * REVISIONS:     09/2006 - created
 */
function on_change_state(state, country) {
  var oForm
  var oElt
  var sCountry

  oForm = document.forms.checkout
  if (!oForm) return
  
  oElt = oForm[country]
  if (!oElt) return

  sCountry = oElt.value
  // if the country is set but is not USA or Canada - clear the state
  if ( (sCountry != "USA")  && (sCountry != "Canada") && (sCountry.length > 0) ) {
    oElt = oForm[state]
    if (oElt) {
      oElt.selectedIndex = 0
      alert("You can only select state if country is USA.")
    }
  }
	
  return
}

/*
 * PURPOSE:       This function is called when user clicks the "Same as billing address" checkbox
 *                Copies values from the billing address to the shipping address fields
 * PARAMETERS:    N/A
 * RETURN VALUE:  N/A
 * REVISIONS:     09/2006 - created
 */
function set_same_address() {
	 var oForm
   var oElt
   var oElt2
   var arr

	oForm = document.forms.checkout
	if (!oForm) return
    
	oElt = oForm.s_sameaddress
	if ( (!oElt) || (!oElt.checked) ) return
    
	oForm.s_firstname.value = oForm.firstname.value
	oForm.s_lastname.value = oForm.lastname.value
  oForm.s_address.value = oForm.address.value
  oForm.s_city.value = oForm.city.value
	oForm.s_zip.value = oForm.zip.value

  oForm.s_country.selectedIndex = oForm.country.selectedIndex
  on_change_country("s_")
	oForm.s_state.selectedIndex = oForm.state.selectedIndex
	
	oForm.s_email.value = oForm.email.value
	oForm.s_phone2.value = oForm.phone2.value
	
	/*
	oForm.s_phone.value = oForm.phone.value
	oForm.s_cellphone.value = oForm.cellphone.value
  */
	
  return
}

/*
 * PURPOSE:       This function clears the "Same as billing address" checkbox
 *                in response to user changing one of the shipping address fields
 * PARAMETERS:    N/A
 * RETURN VALUE:  N/A
 * REVISIONS:     09/2009 - created
 */
function clear_same_address() {
	 var o_form
   var o_elt

	o_form = document.forms.checkout
	if (!o_form) return
    
	o_elt = o_form.s_sameaddress
	if (o_elt) o_elt.checked = false
	
  return
}

/*
 * PURPOSE:       This function is called when user changes a field in the billing address while the "Same as billing address checkbox" is checked
 *                Copies the changed value from the billing address to the corresponding shipping address field
 * PARAMETERS:    elt_name - name of the field that changed
 * RETURN VALUE:  N/A
 * REVISIONS:     08/2006 - created
 */
function set_same_elt(elt_name) {
	var oForm
   var oElt
   var oElt2
   var arr

	oForm = document.forms.checkout
	if (!oForm) return
    
	oElt = oForm.s_sameaddress
	if ( (!oElt) || (!oElt.checked) ) return
	
	oElt = oForm[elt_name]
	if (!oElt) return 
	
	oElt2 = oForm["s_" + elt_name]
	if (!oElt2) return
	
	if (oElt.type == "select-one") {
	  if (oElt2.type == "select-one") oElt2.selectedIndex = oElt.selectedIndex
	} else {
	  oElt2.value = oElt.value
	}
	
	if (elt_name == "country") {
	  on_change_country("s_")
	}
	
	return
}

/*
 * PURPOSE:       This function is called when user changes the Country field on the checkout form
 * PARAMETERS:    prefix   - prefix for the field containing the countries drop-down.
 *                           is either "" (for billing address) or "s_" (for shipping address)
 * RETURN VALUE:  N/A
 * REVISIONS:     09/2006 - created
 */
function on_change_country(prefix) {
	var oForm
	var oState
	var oElt
	var country
	var region
	var i
	var states_arr
	
  oForm = document.forms.checkout
  if (!oForm) return
  oCountry = oForm[prefix + "country"]
  if (!oCountry) return
	oState = oForm[prefix + "state"]
	if (!oState) return 
	
	oState.selectedIndex = 0
	country = oCountry.options[oCountry.selectedIndex].value
	if (country.length == 0) country = "USA"
  // clear the states drop-down
	for (i = oState.options.length - 1; i >= 0; i--) {
	  oState.options[i] = null
	}
  // if country is USA, then add the list of states
	if (country == "USA"){
    oState.options[0] = new Option('','',false,false)
	  states_arr = states();
    for (i = 1; i <= states_arr[0]; i++) {
	    oState.options[i] = new Option(states_arr[i],states_arr[i],false,false)
	  }
	  oState.selectedIndex = 0 
  }
   
  // if country is Canada, then add the list of provinces
  if (country == "Canada") {
    states_arr = provinces();
    for (i = 1; i <= states_arr[0]; i++) {
	    oState.options[i] = new Option(states_arr[i],states_arr[i],false,false)
	  }
	  oState.selectedIndex = 0 
  }
  return
}

/*
 * PURPOSE:       Sets the flag to indicate the order should be saved for later, and submits the Checkout form
 * PARAMETERS:    form_name - name of the form
 * RETURN VALUE:  N/A
 * REVISIONS:     09/2006 - created
 */
function save_for_later(form_name) {
	var o_form
	
	o_form = document.forms[form_name]
	if (o_form) {
	  o_form.unfinished.value = 1
		o_form.submit()
	} 
	
	return 
}

/*
 * PURPOSE:       Check whether all fields in the shipping address contain acceptable values (phone numbers, emails, zip code 
 *                correctly formatted etc)
 * PARAMETERS:    N/A
 * RETURN VALUE:  true - if all shipping address fields contain acceptable values
 *                false - if not
 * REVISIONS:     09/2006 - created
 */
function is_valid_shipping_address() {
	var oForm
   var oElt

	oForm = document.forms.checkout
	if (!oForm) return false
   	
	oElt = oForm.s_firstname
	if (!oElt) return false
	if (oElt.value.length == 0) {
	  alert("Please enter first name for the shipping address.")
	  oElt.focus()
     return false
	}
	
	oElt = oForm.s_lastname
	if (!oElt) return false
	if (oElt.value.length == 0) {
	  alert("Please enter last name for the shipping address.")
	  oElt.focus()
	  return false
	}
	
	oElt = oForm.s_address
	if (!oElt) return false
	if (oElt.value.length == 0) {
	  alert("Please enter the street address for the shipping address.")
	  oElt.focus()
	  return false
	}
	
	oElt = oForm.s_city
	if (!oElt) return false
	if (oElt.value.length == 0) {
	  alert("Please enter city for the shipping address.")
	  oElt.focus()
	  return false
	}
	
	oElt = oForm.s_country

	isUS = true
	if (oElt) isUS = (oElt.options[oElt.selectedIndex].value == "USA")

	oElt = oForm.s_state
	if (!oElt) return false
	if ( (isUS) && ( oElt.options[oElt.selectedIndex].value.length == 0 ) ) {
	  alert("Please enter state for the shipping address.")
	  oElt.focus()
	  return false
	}
	
	oElt = oForm.s_zip
	if (!oElt) return false
	if (oElt.value.length == 0) {
	  alert("Please enter zip code for the shipping address.")
	  oElt.focus()
	  return false
	} 
   // a valid US zip code is 5 or 9 digits
   if (isUS && (!is_valid_zip_code(oElt.value)) ) {
	  alert("Please enter a valid zip code. A valid zip code consists of five digits, optionally followed by - and four more digits. Examples of valid zip codes are: 12345 or 12345-6789.")
	  oElt.focus()
	  return false
   }

	oElt = oForm.s_country
	if (!oElt) return false
	if (oElt.options[oElt.selectedIndex].value.length == 0) {
	  alert("Please enter country for the shipping address.")
	  oElt.focus()
	  return false
	}

   return true
}

/*
 * PURPOSE:      This function shows or hides alternate addresses (if they are shown, this function will hide them;
 *               if they are hidden, this function will show them)
 * PARAMETERS:    N/A
 * RETURN VALUE:  N/A
 * REVISIONS:     09/2006 - created
 */
function show_hide_alternate_addresses() {
  var o_form
	var o_elt
	var num_addresses
	var show_addresses
	var display
	var idx
	
	o_form = document.forms.checkout
	if (!o_form) return 
	
	o_elt = o_form.is_alternate
	if (!o_elt) return
	
	show_addresses = o_elt.checked
	if (show_addresses) { 
	  display = ''
	} else {
	  display = 'none'
	}
	
	o_elt = o_form.num_alt_addresses
	if (!o_elt) return
	
	num_addresses = parseInt(o_elt.value)
	
	for (idx = 1; idx <= num_addresses; idx++) {
	  o_elt = document.getElementById("alt_address_" + idx)
		if ( (!o_elt) && (document.all) ) {
		  o_elt = document.all["alt_address_" + idx]
		}
		if (o_elt) o_elt.style.display = display
	}
	
	return
}
