/******** BEGIN ITEM QUANTITIES ***********/

/*
 * PURPOSE:       Update the total for the specified item and the grand total for the shopping cart
 *                Called when user manually changes wuantity or removes an item
 * PARAMETERS:    target        - URL of the update_cart.php page that updates the $_SESSION variables
 *                which         - ID of the item to update totals for
 *                remove        - flag indicating whether to remove the item from the shopping cart altogether
 *                row_number    - row number of the item in the shopping cart
 * RETURN VALUE:  N/A
 * REVISIONS:     09/2009 - created
 */
function update_total(target, which, remove, row_number) {
  // variables
  var l_quantity
	var l_prev_quantity
	// objects
	var o_form
	var o_quantity
	var o_prev_quantity
	
	if (target == "") return
	
	o_form = document.forms.shopping_cart
	if (!o_form) return
	
  if (remove) {
	  l_quantity = 0
  } else {
		// get the quantity that has changed
		o_quantity = o_form["q" + which]
		if (!o_quantity) return	
		l_quantity = parseIntSafe(o_quantity.value)
	}
	
	o_prev_quantity = o_form["qh" + which]
	if (!o_prev_quantity) return
	l_prev_quantity = parseIntSafe(o_prev_quantity.value)
	
	// prevent page reloading when user just tabs off the field
	if (l_prev_quantity == l_quantity) return
	
	enable_buttons(false)
	
	var handleSuccess = function(o) { 
	    var o_elt
	    var result_string = ""
			var result_arr
 
	    if(o.responseText !== undefined) { 
				result_string = o.responseText.toString().replace(/\n/gi,'');
				result_arr = result_string.split(String.fromCharCode(1))
				// alert(result_arr)
				if (result_is_success(result_arr[0])) {
		    	if (remove) {
						o_quantity = o_form["q" + which]
						if (o_quantity) o_quantity.value = ""
					}
				  // item subtotal
					o_elt = document.getElementById("subtotal" + which)
					if (o_elt) o_elt.innerHTML = result_arr[2]
					// order total
					o_elt = document.getElementById("tdtotal")
					if (o_elt) o_elt.innerHTML = result_arr[3]
					// tax
					o_elt = document.getElementById("tax_total")
					if (o_elt) o_elt.innerHTML = result_arr[4]
					// shipping
					o_elt = document.getElementById("shippingtotal")
					if (o_elt) o_elt.innerHTML = result_arr[5]
					// grand total
					o_elt = document.getElementById("grandtotal")
					if (o_elt) o_elt.innerHTML = result_arr[6]
					// hidden order total
					o_elt = o_form.total
					if (o_elt) o_elt.value = result_arr[7]
					// hidden total quantity
					o_elt = o_form.total_quantity
					if (o_elt) o_elt.value = result_arr[8]
					// alert(result_arr[9] + "\n" + result_arr[10])
					// update shipping methods?
					if (result_arr[9] == "1") {
						// update available shipping methods
						o_elt = document.getElementById("shipping_methods_container")
						if (o_elt) o_elt.innerHTML = result_arr[10]
					}
				} else {
					alert("An error occurred while updating the ordered quantity.")
				}
				enable_buttons(true)
			}
	} 
	
	var handleFailure = function(o) {
	  // don't show an error message since this occurs if the user clicks on a link to a different page
		// while focus is on the gift text field
		//alert("An error occurred while updating the ordered quantity.")
		enable_buttons(true)
	}
	
	var callback = 
	{ 
	  success:handleSuccess, 
	  failure: handleFailure, 
	  argument: [] 
	}; 
	
	var request = YAHOO.util.Connect.asyncRequest('POST', target, callback, "product_id=" + which + "&new_quantity=" + l_quantity + "&remove=" + remove); 
}

/******** END ITEM QUANTITIES ***********/

/******** BEGIN PAYMENT OPTIONS ***********/
function select_payment_option(which, url1, url2, update_option) {
	var o_elt
	var o_form
	
	if (current_payment_option == which) {
		if (which == "express") express_checkout(url2)
	  return
	}
	
	if (update_option) {
	  o_form = document.forms.shopping_cart
		if (!o_form) return
		for (var j = 0; j < o_form.payment_option.length; j++) {
		  if (o_form.payment_option[j].value == which) {
				o_form.payment_option[j].checked = true
			  break
			}
		}
	}
	
	// unselect previous payment option
	o_elt = document.getElementById("po_" + current_payment_option)
	if (!o_elt) return
	o_elt.className = "payment_option"
	/*
	if (current_payment_option == "cc") {
	  // hide credit card info, since the other two options do not use it
		o_elt = document.getElementById("cc_header")
		if (o_elt) o_elt.style.display = "none"
		o_elt = document.getElementById("cc_type")
		if (o_elt) o_elt.style.display = "none"
		o_elt = document.getElementById("cc_num")
		if (o_elt) o_elt.style.display = "none"
		o_elt = document.getElementById("cc_exp")
		if (o_elt) o_elt.style.display = "none"
	}
	*/
	
	// and select the new one
	o_elt = document.getElementById("po_" + which)
	if (!o_elt) return
	o_elt.className = "payment_option_selected"
	if (which == "cc") {
	  // show credit card info
		o_elt = document.getElementById("cc_header")
		if (o_elt) o_elt.style.display = ""
		o_elt = document.getElementById("cc_type")
		if (o_elt) o_elt.style.display = ""
		o_elt = document.getElementById("cc_num")
		if (o_elt) o_elt.style.display = ""
		o_elt = document.getElementById("cc_exp")
		if (o_elt) o_elt.style.display = ""
	}
	
	current_payment_option = which
	
	update_payment_option(url1)
	
	if (which == "express") express_checkout(url2)
}

/*
 * PURPOSE:       Save card type and expiration date in $_SESSION on the server when the user changes them
 * PARAMETERS:    target        - URL of the update_cart.php page that updates the $_SESSION variables
 * RETURN VALUE:  N/A
 * REVISIONS:     11/26/2010 - created
 */
function update_payment_option(target) {
  // variables
	var card_type
	var card_number
  var exp_month
	var exp_year
	// objects
	var o_form
	
	if (target == "") return
	
	o_form = document.forms.shopping_cart
	if (!o_form) return
	
	o_elt = o_form.card_type
	if (!o_elt) return
	card_type = o_elt.options[o_elt.selectedIndex].value
	
	o_elt = o_form.card_number
	if (!o_elt) return
	card_number = o_elt.value
	
	o_elt = o_form.exp_month
	if (!o_elt) return
	exp_month = o_elt.options[o_elt.selectedIndex].value
	
	o_elt = o_form.exp_year
	if (!o_elt) return
	exp_year = o_elt.options[o_elt.selectedIndex].value
	
	enable_buttons(false)
	
	var handleSuccess = function(o) { 
	    var o_elt
	    var o_elt2
	    var result_string = ""
			var result_arr
			var num_items 
			var pos_arr

	    if(o.responseText !== undefined) { 
				result_string = o.responseText.toString().replace(/\n/gi,'');
				result_arr = result_string.split(String.fromCharCode(1))
				if (result_is_success(result_arr[0])) {
				  // nothing to do 
				} else {
					alert("An error occurred while updating credit card information.")
				}
				enable_buttons(true)
			}
	} 
	
	var handleFailure = function(o) {
	  // don't show an error message since this occurs if the user clicks on a link to a different page
		// while focus is on the gift text field
		alert("An error occurred while updating credit card information.")
		enable_buttons(true)
	}
	
	var callback = 
	{ 
	  success:handleSuccess, 
	  failure: handleFailure, 
	  argument: [] 
	}; 
	
	var request = YAHOO.util.Connect.asyncRequest('POST', target, callback, "exp_month=" + exp_month + "&exp_year=" + exp_year + "&card_type=" + card_type + "&card_number=" + card_number + "&payment_option=" + current_payment_option); 
}

/******** END PAYMENT OPTIONS ***********/

/******** BEGIN ADDRESS ***********/

/*
 * PURPOSE:       Update the total for the specified item and the grand total for the shopping cart
 *                Called when user manually changes wuantity or removes an item
 * PARAMETERS:    target        - URL of the update_address.php page that updates the $_SESSION variables
 *                which         - ID of the address field to update, or a |-delimited list of IDs
 * RETURN VALUE:  N/A
 * REVISIONS:     09/2009 - created
 */
function update_address(target, which) {
  // variables
  var params
	var name
	var value
	var arr
	var need_reload
	// objects
	var o_form
	var o_elt
	
	if (target == "") return
	
	o_form = document.forms.shopping_cart
	if (!o_form) return
	
	need_reload = false
	enable_buttons(false)
	
	var handleSuccess = function(o) { 
	    var result_string = ""
			var result_arr
			var pos_arr
			var update_tax
			var update_shipping
	
	    if(o.responseText !== undefined) { 
				result_string = o.responseText.toString().replace(/\n/gi,'');
				result_arr = result_string.split(String.fromCharCode(1))
				// alert(result_string)
				if (result_is_success(result_arr[0])) {
					update_tax = result_arr[4]
					if (update_tax) {
						o_elt = document.getElementById("tax_total")
						if (o_elt) o_elt.innerHTML = result_arr[1]
					}
					
					update_shipping = result_arr[5];
					if (update_shipping) {
					  // update shipping total
						o_elt = document.getElementById("shippingtotal")
						if (o_elt) o_elt.innerHTML = result_arr[2]
						// update available shipping methods
						o_elt = document.getElementById("shipping_methods_container")
						if (o_elt) o_elt.innerHTML = result_arr[3]
					}
					
					if (update_tax || update_shipping) {
						o_elt = document.getElementById("grandtotal")
						if (o_elt) o_elt.innerHTML = result_arr[6]
					}
				} else {
					alert("An error occurred while updating the address information.")
				}
				enable_buttons(true)
			}
	} 
	
	var handleFailure = function(o) {
	  // don't show an error message since this occurs if the user clicks on a link to a different page
		// while focus is on the gift text field
		alert("An error occurred while updating the address information.")
	  enable_buttons(true)
	}
	
	var callback = 
	{ 
	  success:handleSuccess, 
	  failure: handleFailure, 
	  argument: [] 
	}; 
	
	params = ""
	arr = which.split("|")
	for (var j = 0; j < arr.length; j++) {
	  name = arr[j]
		if ((name != "state") && (name != "country")) need_reload = true
		o_elt = o_form[name]
		if (o_elt) { 
		  value = o_elt.value
	    params = (params == "") ? name + "=" + value : params + "&" + name + "=" + value
		}
	}

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

/*
 * 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 o_form
  var o_elt
  var s_country

  o_form = document.forms.shopping_cart
  if (!o_form) return
  
  o_elt = o_form[country]
  if (!o_elt) return

  s_country = o_elt.value
  // if the country is set but is not USA or Canada - clear the state
  if ( (s_country != "USA")  && (s_country != "Canada") && (s_country.length > 0) ) {
    o_elt = o_form[state]
    if (o_elt) {
      o_elt.selectedIndex = 0
      alert("You can only select state/province if country is USA or Canada.")
    }
  }
	
  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 o_form
	var o_state
	var country
	var i
	var states_arr
	
  o_form = document.forms.shopping_cart
  if (!o_form) return
  o_country = o_form[prefix + "country"]
  if (!o_country) return
	o_state = o_form[prefix + "state"]
	if (!o_state) return 
	
	o_state.selectedIndex = 0
	country = o_country.options[o_country.selectedIndex].value
	if (country.length == 0) country = "USA"
  // clear the states drop-down
	for (i = o_state.options.length - 1; i >= 0; i--) {
	  o_state.options[i] = null
	}
  // if country is USA, then add the list of states
	if (country == "USA"){
    o_state.options[0] = new Option('','',false,false)
	  states_arr = states();
    for (i = 1; i <= states_arr[0]; i++) {
	    o_state.options[i] = new Option(states_arr[i],states_arr[i],false,false)
	  }
	  o_state.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++) {
	    o_state.options[i] = new Option(states_arr[i],states_arr[i],false,false)
	  }
	  o_state.selectedIndex = 0 
  }
  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:    url1 - URL of the update_address.php page that updates the $_SESSION variables
 * RETURN VALUE:  N/A
 * REVISIONS:     09/2006 - created
 */
function set_same_address(url1) {
	 var o_form
   var o_elt
   var arr

	o_form = document.forms.shopping_cart
	if (!o_form) return
    
	o_elt = o_form.s_sameaddress
	if (!o_elt) return
	if (!o_elt.checked) {
	  update_address(url1, 's_sameaddress')
	  return
  }
	
	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
  on_change_country("s_")
	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
	
	update_address(url1, 's_sameaddress|s_firstname|s_lastname|s_address|s_city|s_zip|s_state|s_country|s_email|s_phone2')
  return
}

/*
 * PURPOSE:       This function clears the "Same as billing address" checkbox
 *                in response to user changing one of the shipping address fields
 * PARAMETERS:    url1  - URL of the update_address.php page that updates the $_SESSION variables
 *                which - name of the shipping address field that was changed
 * RETURN VALUE:  N/A
 * REVISIONS:     09/2009 - created
 */
function clear_same_address(url1, which) {
	 var o_form
   var o_elt

	o_form = document.forms.shopping_cart
	if (!o_form) return
    
	o_elt = o_form.s_sameaddress
	if (o_elt) {
	  o_elt.checked = false
	  update_address(url1, 's_same_address|s_firstname|s_lastname|s_address|s_city|s_zip|s_state|s_country|s_email|s_phone2')
	}
	
  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:    url1  - URL of the update_address.php page that updates the $_SESSION variables
 *                which - name of the billing address field that was changed
 * RETURN VALUE:  N/A
 * REVISIONS:     08/2006 - created
 */
function set_same_elt(url1, which) {
	 var o_form
	 var o_same_address
   var o_billing_field
   var o_shipping_field
   var arr

	o_form = document.forms.shopping_cart
	if (!o_form) return
    
	o_same_address = o_form.s_sameaddress
	if ( (!o_same_address) || (!o_same_address.checked) ) {
		update_address(url1, which)
	  return
	}
	
	o_billing_field = o_form[which]
	if (!o_billing_field) return 
	
	o_shipping_field = o_form["s_" + which]
	if (!o_shipping_field) return
	
	if (o_billing_field.type == "select-one") {
	  if (o_shipping_field.type == "select-one") o_shipping_field.selectedIndex = o_billing_field.selectedIndex
	} else {
	  o_shipping_field.value = o_billing_field.value
	}
	
	if (which == "country") {
	  on_change_country("s_")
		update_address(url1, "country|state|s_state|s_country")
	} else {
	  if (which == "state") { 
			on_change_state("s_")
			update_address(url1, "country|state|s_state|s_country")
	  } else {
		  update_address(url1, which + "|s_" + which)
		}
	}
	
	return
}

/*
 * 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.shopping_cart
	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
}
/******** END ADDRESS ***********/

/******** BEGIN GIFT TEXT ***********/

/*
 * PURPOSE:      This function shows or hides the gift text box (if they are shown, this function will hide them;
 *               if they are hidden, this function will show them)
 * PARAMETERS:    target        - URL of the update_gift_info.php page that updates the $_SESSION variables
 * RETURN VALUE:  N/A
 * REVISIONS:     11/2010 - created
 */
function check_is_gift(target) {
  var o_form
  var o_elt
  var is_gift

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

  o_elt = o_form.is_gift
  if (!o_elt) return 
			 
  is_gift = o_elt.checked 
  
  o_elt = get_element("gifttexttr")
  if (!o_elt) return

  if (is_gift) {
	  // show gift text field
    o_elt.style.display = '' 
    o_elt = o_form.gift_text
    if (o_elt) o_elt.focus()  
  } else {
	  // hide gift text field
    o_elt.style.display = 'none'
    o_elt = o_form.gift_text
	  if (o_elt) o_elt.value = ''
  }
  
	update_gift_info(target)
	
  return 
}

/*
 * PURPOSE:       This function sends updated gift text information to the server
 *                and updates the grand total for the order
 * PARAMETERS:    target        - URL of the update_gift_info.php page that updates the $_SESSION variables
 * RETURN VALUE:  N/A
 * REVISIONS:     11/2010 - created
 */
function update_gift_info(target) {
  // variables
	var is_gift
	var gift_text
	// objects
	var o_form
	var o_elt
	
	if (target == "") return
	
	o_form = document.forms.shopping_cart
	if (!o_form) return
	
	// Disable all buttons while the information is being sent to the server
	enable_buttons(false)
	
	var handleSuccess = function(o) { 
	    var result_string = ""
			var result_arr
			var pos_arr
			
	    if(o.responseText !== undefined) { 
				result_string = o.responseText.toString().replace(/\n/gi,'');
				result_arr = result_string.split(String.fromCharCode(1))
				if (result_is_success(result_arr[0])) {
					o_elt = document.getElementById("gifttotal")
					if (o_elt) o_elt.innerHTML = result_arr[2]
					o_elt = document.getElementById("grandtotal")
					if (o_elt) o_elt.innerHTML = result_arr[1]
				} else {
					alert("An error occurred while updating the gift information.")
				}
			}
		  enable_buttons(true)			
	} 
	
	var handleFailure = function(o) {
	  // don't show an error message since this occurs if the user clicks on a link to a different page
		// while focus is on the gift text field
		// alert("An error occurred while updating the gift information.")
	  enable_buttons(true)
	}
	
	var callback = 
	{ 
	  success:handleSuccess, 
	  failure: handleFailure, 
	  argument: [] 
	}; 

	// Get the values to be sent to the server	
	o_elt = o_form.is_gift
	if (!o_elt) return
	is_gift = (o_elt.checked) ? 1 : 0
	
	o_elt = o_form.gift_text
	if (!o_elt) return
	gift_text = o_elt.value
	
	var request = YAHOO.util.Connect.asyncRequest('POST', target, callback, "is_gift=" + is_gift + "&gift_text=" + gift_text); 
}
/******** END GIFT TEXT ***********/

/******** BEGIN UPDATE SHIPPING ***********/

function update_shipping(target) {
  // variables
	var f_shipping
	// objects
	var o_form
	var o_shipping_method
	var o_shipping_cost
	
	if (target == "") return
	
	o_form = document.forms.shopping_cart
	if (!o_form) return
	
	// Disable all buttons while the information is being sent to the server
	enable_buttons(false)
	
	var handleSuccess = function(o) { 
	    var result_string = ""
			var result_arr
			var o_elt
			
	    if(o.responseText !== undefined) { 
				result_string = o.responseText.toString().replace(/\n/gi,'');
				result_arr = result_string.split(String.fromCharCode(1))
				if (result_is_success(result_arr[0])) {
				  o_elt = document.getElementById("shippingtotal")
					if (o_elt) o_elt.innerHTML = result_arr[2]
				  o_elt = document.getElementById("grandtotal")
					if (o_elt) o_elt.innerHTML = result_arr[1]
				} else {
					alert("An error occurred while updating the gift information.")
				}
			}
		  enable_buttons(true)			
	} 
	
	var handleFailure = function(o) {
	  // don't show an error message since this occurs if the user clicks on a link to a different page
		// while focus is on the gift text field
		// alert("An error occurred while updating the gift information.")
	  enable_buttons(true)
	}
	
	var callback = 
	{ 
	  success:handleSuccess, 
	  failure: handleFailure, 
	  argument: [] 
	}; 

	// Get the values to be sent to the server	
  o_shipping_method = o_form.shippingmethod
	if (!o_shipping_method) return
	
	// set shipping
  o_shipping_cost = o_form['cost' + o_shipping_method.selectedIndex]
	if (o_shipping_cost) {
    f_shipping = parse_currency(o_shipping_cost.value) 
	} else {
    f_shipping = 0
  }	
	
	var request = YAHOO.util.Connect.asyncRequest('POST', target, callback, "shippingmethod=" + o_shipping_method.value + "&shipping=" + f_shipping); 

  return
}

/******** END UPDATE SHIPPING ***********/

/******** BEGIN HELPER FUNCTIONS ***********/

/*
 * PURPOSE:       Display a warning message that more items have been selected than are available
 * PARAMETERS:    q - available quantity of an item
 *                n - item name
 * RETURN VALUE:  N/A
 * REVISIONS:     09/2009 - created
 */
function avail_quantity_message(q,n) {
  if (q < 1) return "There is no " + n + " left in the store."
  if (q == 1) return "There is only one " + n + " left in the store."
  if (q > 1) return "There are only " + q + " " + n + " items left in the store."
	return ""  
}

/*
 * PURPOSE:       This function enables or disables buttons so the user cannot update the form
 *                while the page is being updated
 * PARAMETERS:    enabled - if true, enable the buttons
 *                          if false, disable the buttons
 * RETURN VALUE:  N/A
 * REVISIONS:     09/2006 - created
 */
function enable_buttons(enabled) { 
  var o_form
	
	o_form = document.forms.shopping_cart
	if (o_form.continue_shopping) o_form.continue_shopping.disabled = !enabled
	if (o_form.return_to_wish_list) o_form.return_to_wish_list.disabled = !enabled
	if (o_form.return_to_product) o_form.return_to_product.disabled = !enabled
	if (o_form.clear) o_form.clear.disabled = !enabled
	if (o_form.paypalbtn) o_form.paypalbtn.disabled = !enabled
	if (o_form.printandmailbtn) o_form.printandmailbtn.disabled = !enabled
  return
}

/*
 * PURPOSE:       This function enables or disables all fields so the user cannot update the form
 *                while the page is being redirected to PayPal or to process payment
 * PARAMETERS:    enabled - if true, enable all form fields
 *                          if false, disable all form fields
 * RETURN VALUE:  N/A
 * REVISIONS:     12/2010 - created
 */
function enable_fields(enabled) { 
  var o_form
	var o_elt
	
	o_form = document.forms.shopping_cart
	if (!o_form) return
	
	for (j = 1; j <= o_form.elements.length; j++) {
	  o_elt = o_form.elements[j]
		if (o_elt) o_elt.disabled = !enabled
	}
	
  return
}


/******** END HELPER FUNCTIONS ***********/

/******** BEGIN CLEAR CART ***********/

/*
 * PURPOSE:       Clear the shopping cart
 * PARAMETERS:    target - url of the file that clears the $_SESSION information on the server
 * RETURN VALUE:  N/A
 * REVISIONS:     09/2009 - created
 */
function clear_cart(target) {	
  if (!window.confirm("Are you sure you would like to clear all items from your shopping cart?\nTo clear all items, click OK.\nTo return to the order, click Cancel.")) {
    return
  }
	
  if (target == "") return

	var	o_elt = document.getElementById("shopping_cart_items")
	if (!o_elt) return
		
	var handleSuccess = function(o){ 
	    var o_elt2
	    var result_string = ""
			var result_arr
			
	    if(o.responseText !== undefined) { 
				result_string = o.responseText.toString().replace(/\n/gi,'');
				result_arr = result_string.split(String.fromCharCode(1))
				if (parseInt(result_arr[0]) == 1) {
					o_elt.innerHTML = '<span class="error">Your shopping cart is empty.</span><br><br><span class="error"><input type="button" class="button" onclick="location.href=\'' + result_arr[1] + 'products/products.php\';" value="Start Shopping"></span>'
					o_elt2 = document.getElementById("shopping_cart_title")
					if (o_elt2) o_elt2.innerHTML = "Your Shopping Cart and Secure Checkout Page&nbsp;(empty)"
				} else {
					o_elt.innerHTML = '<span class="error">An error occurred while clearing all items from the shopping cart.</span>'
				}
				// o_elt.style.height = "280px"				
			}
	} 
	
	var handleFailure = function(o) {
		o_elt = document.getElementById("shopping_cart_items")
		if (o_elt) {
		  o_elt.innerHTML = '<span class="error">An error occurred while clearing all items from the shopping cart.</span>'		
		}
	}
	
	var callback = 
	{ 
	  success:handleSuccess, 
	  failure: handleFailure, 
	  argument: [] 
	}; 
	
	var request = YAHOO.util.Connect.asyncRequest('POST', target, callback, ""); 
}

/******** END CLEAR CART ***********/

/******** BEGIN SUBMIT FORM ***********/

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

	if (!validate_shopping_cart(target)) return

	order_being_processed_message()
  // if (o_form.payment_option.value != "check") {  }
	o_form.submit()
	
  return
}

/*
 * PURPOSE:       send PayPal Express Checkout authorization request
 * PARAMETERS:    target - url of the file that sends PayPal Express Checkout authorization request
 * RETURN VALUE:  N/A
 * REVISIONS:     12/2010 - created
 */
function express_checkout(target) {
  var o_form
		
  if (target == "") return
	
	o_form = document.forms.shopping_cart
	if (!o_form) return
	if (o_form.token.value != "") return
	
  if (!validate_items()) return
	
	paypal_redirect_message()
	enable_fields(false)
	
	var handleSuccess = function(o){ 
	    var o_elt2
	    var result_string = ""
			var result_arr
			
	    if(o.responseText !== undefined) { 
				result_string = o.responseText.toString().replace(/\n/gi,'');
				result_arr = result_string.split(String.fromCharCode(1))
				if (parseInt(result_arr[0]) == 1) {
				  o_form.token.value = result_arr[1]
					location.href = result_arr[2]
				} else {
					YAHOO.example.paypal_redirect.panel.hide()
					alert("An error occurred while sending request to PayPal.\n" + result_arr[1])
					enable_fields(true)
					o_form.token.value = ""
				}
			}
	} 
	
	var handleFailure = function(o) {
		YAHOO.example.paypal_redirect.panel.hide()
		alert("An error occurred while sending request to PayPal.")
		enable_fields(true)
	  o_form.token.value = ""
	}
	
	var callback = 
	{ 
	  success:handleSuccess, 
	  failure: handleFailure, 
	  argument: [] 
	}; 
	
	var request = YAHOO.util.Connect.asyncRequest('POST', target, callback, ""); 
}

/******** END SUBMIT FORM ***********/

/******** BEGIN VALIDATION FUNCTIONS ***********/

/*
 * PURPOSE:       Validate that the user can proceed to checkout (at least one item in the shopping cart, and quantity selected
 *                for each item does not exceed the available quantity for that item)
 * PARAMETERS:    target - url of the update_payment_option.php page
 * RETURN VALUE:  true   - if it's OK to proceed to checkout
 *                false  - if not (either no items selected, or quantity selected for an item exceeds tha available quantity for that item)
 * REVISIONS:     09/2009 - created
 */
function validate_shopping_cart(target) {
  if (!validate_items()) return false
	if (!validate_address(target)) return false
	if (!validate_shipping()) return false
	if (!validate_card_info()) 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?")) {
	  return  true
	} 
	
	return false
}

/*
 * PURPOSE:       Validate that the user can submit the shopping cart form (at least one item in the shopping cart, and quantity selected
 *                for each item does not exceed the available quantity for that item)
 * PARAMETERS:    
 * RETURN VALUE:  true - if it's OK to proceed to checkout
 *                false - if not (either no items selected, or quantity selected for an item exceeds tha available quantity for that item)
 * REVISIONS:     09/2009 - created
 */
function validate_items() { 
  // variables
	var f_total
	var i
	var name
	var productId
	var productName
	var lQ
	var lAQ 
	var result
  var total_quantity
	// objects
	var oTotal
	var o_form
	var oElt
	var oElt2
	var MIN_ORDER_TOTAL
	
	MIN_ORDER_TOTAL = 0
	
	o_form = document.forms.shopping_cart
	if (!o_form) return false
		
	oTotal = o_form.total
	if (!oTotal) return false
	//alert(striptags(oTotal.value))
	f_total = parseFloatSafe(getDollarAmt(striptags(oTotal.value)))
  //alert(f_total)
	
	if (!(f_total > 0)) {
	  alert("You have not selected any products to purchase.")
	  return false
	}
	
	if (f_total <= MIN_ORDER_TOTAL) {
	  alert("Your order total " + format_string(new String(f_total),"currency") + " is less than the minimum allowed order amount " + format_string(new String(MIN_ORDER_TOTAL),"currency") + ".")
	  return false
	}
	
  total_quantity = 0

	result = true
	for (i = 0; i < o_form.elements.length; i++) {
	  oElt = o_form.elements[i]
		if (oElt) {
		  name = oElt.name
			if (name.substr(0,1) == "q") {
			  lQ = parseIntSafe(oElt.value)
			  productId = name.substr(1)
				oElt2  = o_form["n" + productId]
				if (oElt2) {
				  productName = oElt2.value
					oElt2 = o_form["av" + productId]
					lAQ = parseIntSafe(oElt2.value)
					if (lQ > lAQ) {
						alert(avail_quantity_message(lAQ,productName) + "\nPlease update the selected quantity.")
						oElt.focus()
						result = false
						break
					} else {
            total_quantity = total_quantity + lQ
          }
				}
			}
		}
	}
  
	if (!result) return false
	
  o_form.total_quantity.value = total_quantity
  
	return true
} 

/*
 * PURPOSE:       Validate credit card information (card type, number, and expiration date)
 * PARAMETERS:    N/A
 * RETURN VALUE:  true - if all the fields contain acceptable values, and required fields are non-blank
 *                false - otherwise
 * REVISIONS:     11/2010 - created
 */
function validate_card_info() { 
	var o_form
	var o_elt
	var payment_option
	
	o_form = document.forms.shopping_cart
	if (!o_form) return false
	
	payment_option = ""
	for (var j = 0; j < o_form.payment_option.length; j++) { 
	  if (o_form.payment_option[j].checked) {
		  payment_option = o_form.payment_option[j].value
			break
		}
	}
	
	if (payment_option == "") {
	  alert("Please select payment option.")
		return false
	}
	
	// card info is not required in paying by check or PayPal
	if (payment_option != "cc") return true
	
	// if paying by credit card, make sure that all fields are entered
	if (!validate('shopping_cart','card_type|card_number|exp_month|exp_year','Please select your credit card type.|Please enter your card number.|Please select the month in which your card expires.|Please select the year in which your card expires.','|||','|||',false)) return false

	return true
}

/*
 * PURPOSE:      Validates billing and shipping address information on the shopping cart form
 * PARAMETERS:    target - URL of the update_payment_option.php page
 * RETURN VALUE:  true   - if all the fields contain acceptable values, and required fields are non-blank
 *                false  - otherwise
 * REVISIONS:     09/2009 - created
 */
function validate_address(target){
  // variables
  var fTotal
	var country
	var payment_option
  // objects
  var o_form
  var o_elt	
	
	o_form = document.forms.shopping_cart
	if (!o_form) return false
	
	if (!validate('shopping_cart','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*country||1','||||Please enter a valid zip code.||Please enter a valid email address.',false)) return false

	payment_option = ""
	for (var j = 0; j < o_form.payment_option.length; j++) { 
	  if (o_form.payment_option[j].checked) {
		  payment_option = o_form.payment_option[j].value
			break
		}
	}

  o_country = o_form.country
	if (!o_country) {
		if (payment_option != "check") { 
			if (confirm("Our payment gateway, PayPal, can only accept payments from certain countries.\nWe are unable to determine the country of your billing address and therefore cannot accept your payment online.\nWould you like to automatically change the payment method to 'Mail US a Check'?")) {
				select_payment_option('check', target, '', true)
			} else {
				return false
			}
		}
		
	} else {
	  country = o_country.value
	  if ((country == "USA")  && (o_form.state.selectedIndex < 1)) {
		  alert("Please select your state.")
			set_focus("shopping_cart", "state")
			return false
		}
	  if ((country == "Canada")  && (o_form.state.selectedIndex < 1)) {
		  alert("Please select your province.")
			set_focus("shopping_cart", "state")
			return false
		}
		
	  if ((!allows_pay_pal(country)) && (payment_option != "check")) {
	    if (confirm("You cannot pay with credit card or PayPal from " + country + ". Would you like to automatically change the payment method to 'Mail Us a Check'?")) {
				select_payment_option('check', target, '', true)
		  } else {
        return false
      }
	  }
  }
	
	o_elt = o_form.s_sameaddress
	if (!o_elt) {
		alert("Internal error - missing shipping address information.")
	  return false
	}
	
	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.checked = false
  }

  // If shipping address is not the same as the billing address, validate shipping address separately
  if (!o_elt.checked) {
	  if (!validate("shopping_cart","s_firstname|s_lastname|s_address|s_city|s_zip|s_country", "Please enter recipient's first name.|Please enter recipient's last name.|Please enter recipient's street address.|Please enter recipient's city.|Please enter recipient's postal code.|Please select recipient's country.","||||3*s_country|","||||Please enter a valid zip code.|",false)) return false
		o_country = o_form.s_country
		if (!o_country) {
			alert("Unable to determine the country for the shipping address.")
			return false
		}
	  country = o_country.value
	  if ((country == "USA")  && (o_form.s_state.selectedIndex < 1)) {
		  alert("Please select recipient's state.")
			set_focus("shopping_cart", "s_state")
			return false
		}
	  if ((country == "Canada")  && (o_form.s_state.selectedIndex < 1)) {
		  alert("Please select recipient's province.")
			set_focus("shopping_cart", "s_state")
			return false
		}
	}
	
	return true 
} 

function validate_shipping(){
  // objects
  var o_form
  var o_elt	
	
	o_form = document.forms.shopping_cart
	if (!o_form) return false
	
  o_elt = o_form.shippingmethod
	if (!o_elt) return false

	if (o_elt.selectedIndex == 0) {
	  alert("Please select a shipping method.")
    o_elt.focus()
    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 == "Belgium") || (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")
}

function parse_currency(str) {
  var l_start_pos
	var l_end_pos
	var s_amt
	
	l_start_pos = str.indexOf("$")
	if (l_start_pos == -1) l_start_pos = 0
	l_end_pos = str.indexOf("[")
	if (l_end_pos == -1) {
	  s_amt = str.substr(l_start_pos)
	} else {
	  s_amt = str.substr(l_start_pos,l_end_pos-l_start_pos)
	}
	
	// alert(l_start_pos + "\n" + l_end_pos + "\n!" + s_amt + "!")
	
	return s_amt
}

function validate_gift_card() {
  var o_form
	
  if (validate('shopping_cart','giftcardamount|firstname|s_firstname|lastname|s_lastname|address|city|zip|country|email|s_email|phone2','Please select the gift card amount.|Please enter your first name.|Please enter gift card recipient\'s first name.|Please enter your last name.|Please enter gift card recipient\'s last name.|Please enter your street address.|Please enter your city.|Please enter your zipcode.|Please select your country.|Please enter your email address.|Please enter gift card recipient\'s email address.|Please enter your home phone number.','|||||||||1|1|2','|||||||||Please enter a valid email address.|Please enter a valid email address.|Please enter a valid phone number. A valid phone number must contain area code then number separated by dashes (example: 608-555-5555).')) {
    o_form = document.forms.shopping_cart
		if (o_form) o_form.submit()
	}	
}
