/*
 * 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
 *                n - item name
 * RETURN VALUE:  N/A
 * REVISIONS:     09/2009 - created
 */
function update_total(target, which, remove, row_number) {
  // variables
  var lQuantity
	var fPrice
	var fPrevProductTotal
	var fProductTotal
	var fTotal
	// objects
	var oProductTotal
	var oQuantity
	var oPrice
	var oTotal
	var oForm
	var oGrandTotal
	var o_tr
	var o_pieces_ordered
	var o_package_quantity
	
	if (target == "") return
	
	oForm = document.forms.shopping_cart
	if (!oForm) return
	
  if (remove) {
	  lQuantity = 0
  } else {
		// get the quantity that has changed
		oQuantity = oForm["q" + which]
		if (!oQuantity) return	
		lQuantity = parseIntSafe(oQuantity.value)
	}
	
	var handleSuccess = function(o) { 
	    var o_elt
	    var o_elt2
	    var result_string = ""
			var result_arr
			var num_items 
			
	    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) {
					num_items = parseInt(result_arr[1])
				
					o_package_quantity = oForm["u" + which]
					o_pieces_ordered = document.getElementById("np" + which)
					if ( (o_pieces_ordered) && (o_package_quantity) ) o_pieces_ordered.innerHTML = parseIntSafe(o_package_quantity.value) * lQuantity
					
					oPrice = oForm["p" + which]
					if (!oPrice) return
					fPrice = oPrice.value
					
					oProductTotal = document.getElementById("subtotal" + which)
					if (!oProductTotal) return
					fPrevProductTotal = parseFloatSafe(getDollarAmt(striptags(oProductTotal.innerHTML)))
				
					fPrice = parseFloatSafe(fPrice)
					lQuantity = parseIntSafe(lQuantity)	
					fProductTotal = fPrice * lQuantity
					
					// use the hidden form variable
					oTotal = oForm.total
					if (!oTotal) return
					
					fTotal = parseFloatSafe(oTotal.value)
					fTotal = fTotal - fPrevProductTotal + fProductTotal
					// save new total in the hidden form element
					oTotal.value = fTotal
				
					// show new sub total for the product that was changed  
					if (remove) {
					  if (num_items < 1) {
		          o_elt = document.getElementById("shopping_cart_items")
							if (o_elt) 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[2] + 'products/products.php\';" value="View Galleries"></span>'
						} else { 
						  // hide row
							o_tr = document.getElementById("tr" + row_number)
							if (o_tr) o_tr.style.display = "none"
							// show new total
							oTotal = document.getElementById("tdtotal")
							if (oTotal) oTotal.innerHTML = "<strong>$" + format_string(new String(fTotal),"currency") + "</strong>"
						}
					} else {
					  oProductTotal.innerHTML = "$" + format_string(new String(fProductTotal),"currency")
						// show new total
						oTotal = document.getElementById("tdtotal")
						if (oTotal) oTotal.innerHTML = "<strong>$" + format_string(new String(fTotal),"currency") + "</strong>"
					  oQuantity.focus()
					}
					
					o_elt2 = document.getElementById("shopping_cart_breadcrumb")
					if (o_elt2) {
					  if (num_items < 1) { 
						  o_elt2.innerHTML = "Shopping Cart&nbsp;(empty)" 
						} else {
						  if (num_items == 1) {
   						  o_elt2.innerHTML = "Shopping Cart&nbsp;(1 item)"
							} else {
   						  o_elt2.innerHTML = "Shopping Cart&nbsp;(" + num_items + " items)"
							}
						}
					}
				
				} else {
					alert("An error occurred while updating the ordered quantity.")
				}
			}
	} 
	
	var handleFailure = function(o) {
		alert("An error occurred while updating the ordered quantity.")
	}
	
	var callback = 
	{ 
	  success:handleSuccess, 
	  failure: handleFailure, 
	  argument: [] 
	}; 
	
	var request = YAHOO.util.Connect.asyncRequest('POST', target, callback, "product_id=" + which + "&new_quantity=" + lQuantity + "&remove=" + remove); 
}

/*
 * 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:    
 * 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(){
  // variables
	var fTotal
	var i
	var name
	var productId
	var productName
	var lQ
	var lAQ 
	var result
  var total_quantity
	// objects
	var oTotal
	var oForm
	var oElt
	var oElt2
	var MIN_ORDER_TOTAL
	
	MIN_ORDER_TOTAL = 0
	
	oForm = document.forms.shopping_cart
	if (!oForm) return false
		
	oTotal = oForm.total
	if (!oTotal) return false
	//alert(striptags(oTotal.value))
	fTotal = parseFloatSafe(getDollarAmt(striptags(oTotal.value)))
  //alert(fTotal)
	
	if (!(fTotal > 0)) {
	  alert("You have not selected any products to purchase.")
	  return false
	}
	
	if (fTotal <= MIN_ORDER_TOTAL) {
	  alert("Your order total " + format_string(new String(fTotal),"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 < oForm.elements.length; i++) {
	  oElt = oForm.elements[i]
		if (oElt) {
		  name = oElt.name
			if (name.substr(0,1) == "q") {
			  lQ = parseIntSafe(oElt.value)
			  productId = name.substr(1)
				oElt2  = oForm["n" + productId]
				if (oElt2) {
				  productName = oElt2.value
					oElt2 = oForm["av" + productId]
					lAQ = parseIntSafe(oElt2.value)
					// *** 
					if ( (lQ > lAQ) && (lAQ > 0) ) {
						alert(avail_quantity_message(lAQ,productName) + "\nPlease update the selected quantity.")
						oElt.focus()
						result = false
						break
					} else {
            total_quantity = total_quantity + lQ
          }
				}
			}
		}
	}

  if (result) oForm.total_quantity.value = total_quantity

	return result
} 

/*
 * 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:       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="View Galleries"></span>'
					o_elt2 = document.getElementById("shopping_cart_breadcrumb")
					if (o_elt2) o_elt2.innerHTML = "Shopping Cart&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>'		
			o_elt.style.height = "280px"
		}
	}
	
	var callback = 
	{ 
	  success:handleSuccess, 
	  failure: handleFailure, 
	  argument: [] 
	}; 
	
	var request = YAHOO.util.Connect.asyncRequest('POST', target, callback, ""); 
}
