// JavaScript by Michael Angeletti - Ultracart Pro Services

if(window.parent.document.location.protocol == 'http:')
{
	window.location = 'https://www.cigacease.com/buycigacease.php';
}

var $j = jQuery.noConflict();
var lastShippingEstimates = null;
var buySAFEOnClick = null;
var squareClicked = null;
$j("document").ready(function(){
	try
	{
		cart = getCartInstance();
		if(cart != null)
		{
			cart.paymentMethod = PAYMENT_METHOD_CREDIT_CARD;
		}
		
		
		choosePaymentMethod();
		
		
		// Input allowed countries
		
		var allowedCountries = getAllowedCountries();
		
		if(allowedCountries && allowedCountries.length > 0)
		{
			var countrySelectHtml = '';
			for(i = 0; i < allowedCountries.length; i ++)
			{
				if(allowedCountries[i] == 'United States')
				{
					countrySelectHtml += '<option selected="selected">' + String(allowedCountries[i]) + '</option>\n';
				}
				else
				{
					countrySelectHtml += '<option>' + String(allowedCountries[i]) + '</option>\n'
				}
			}
			$j('#shippingCountry').html(countrySelectHtml);
			$j('#billingCountry').html(countrySelectHtml);
		}
		
		
		
		
		
		
		
		
		// Update city / provinces when country is changed
		
		$j('#shippingCountry').change(function(event){
			$j('#shippingCountry').blur(function(event){
				updateStatesProvinces($j('#shippingCountry').val(), 'shippingState');
			});
		});
		
		
		$j('#billingCountry').change(function(event){
			$j('#billingCountry').blur(function(event){
				updateStatesProvinces($j('#billingCountry').val(), 'billingState');
			});
		});
		
		
		
		
		
		
		
		
		if(getParameterValues("error") != null && getParameterValues("error").length > 0)
		{
			updateStatesProvinces(cart.shipToCountry, 'shippingState');
			updateStatesProvinces(cart.billToCountry, 'billingState');
			inputAddressValues();
			displayQueryErrors();
		}
		
		
		
		
		
		
		
		
		// Toggle billing address
		
		$j('#billingSameAsShipping').click(function(event){
			hideShowBillingAddress();
		});
		
		
		
		
		
		
		
		
		// Toggle payment methods
		
		$j('#paymentChoices input[type=radio]').click(function(){
			choosePaymentMethod();
		});
		
		
		
		
		$j('[name=ADD]').click(function(event){
			
			var currItemId = $j(this).val();
			
			$j('[name=ADD]').each(function()
			{
				
			if(currItemId == $j(this).val())
			{
				this.checked == true;
		
			}else
			{
				this.checked == false;
			}

			});

			addItemsToCart();
		});

		
		
		
		// Click on a product in the table version
		
		$j('.price_col').click(function(event){
			event.preventDefault();
			$j(this).attr('class', 'loading_product');
			window.setTimeout("squareClicked('" + $j(this).children('a').attr('title') + "');", 25);
		});
		
		
		
		addItemsToCart();		
		
		
		// Click on a check box
		
		$j('product_row_desc_row input[type=checkbox]').parent('div').click(function(event){
			try
			{
				if($j(this).children('input')[0].checked == false)
				{
					$j(this).children('input')[0].checked = true;
					
					hideUncheckedProducts();
					removeItem($j(this).children('input')[0].val());
					displayCartDetails();
					calculateShipping();
					scrollToCheckout();
				}
				else
				{
					$j(this).children('input')[0].checked = true;
					
					addItemToCart($j(this).children('input')[0].val());
					showAllProducts();
					hideCartDetails();
					scrollToProducts();
				}
				
				styleCheckMarksForItemsInCart();
			}
			catch(e)
			{
				handleError('Click on check box', e);
			}
		});
		
		
		
		
		
		
		
		
		// Update cart if needed when shipping inputs are blurred
		
		$j('#shippingAddress1').blur(function(){
			updateShippingIfNeeded();
		});
		$j('#shippingAddress2').blur(function(){
			updateShippingIfNeeded();
		});
		$j('#shippingCity').blur(function(){
			updateShippingIfNeeded();
		});
		$j('#shippingState').blur(function(){
			updateShippingIfNeeded();
		});
		$j('#shippingPostalCode').blur(function(){
			updateShippingIfNeeded();
		});
		$j('#shippingCountry').blur(function(){
			updateShippingIfNeeded();
		});
		
		
		
		
		
		
		
		
		
		// Click on 'finalize order' button
		
		$j("#finalize_order button").click(function(event){
			event.preventDefault();
			$j("#finalize_order button").attr('disabled', 'disabled');
			$j("#finalize_order button").attr('class', 'clicked');
			setAddress();
			setPaymentInfo();
			updateCart();
			calculateShippingSync();
			var errors = validateAll();
			if(errors != null && errors.length > 0)
			{
				$j("#finalize_order button").removeAttr('disabled');
				$j("#finalize_order button").removeAttr('class');
				displayCartErrors(errors);
				pulseFirstEmptyInput();
			}
			else
			{
				completeOrder();
			}
		});
		
		
		
		
		
		
		
		
		// Paypal Checkout option if it's available
		
		if(cart.hasPayPal)
		{
			if(cart.payPalCompatible)
			{
				$j('#paypalCheckout').attr('src', cart.payPalButtonUrl);
				$j('#paypalCheckout').attr('alt', cart.payPalButtonAltText);
				$j('#paypal_checkout').show();
				$j("#paypalCheckout").click(function(event){
					event.preventDefault();
					setAddress();
					setPaymentInfo();
					updateCart();
					paypalCompleteOrder();
				});
				$j('#paymentChoices').show();
				$j('#paymentChoicePaypalRow').show();
			}
		}
		
		
		
		
		
		
		
		
		// Google checkout option if it's available
		
		if(cart.hasGoogleCheckout)
		{
			if(cart.googleCheckoutCompatible)
			{
				$j('#googleCheckout').attr('src', cart.googleCheckoutButtonUrl);
				$j('#googleCheckout').attr('alt', cart.googleCheckoutButtonAltText);
				$j('#google_checkout').show();
				$j("#googleCheckout").click(function(event){
					event.preventDefault();
					setAddress();
					setPaymentInfo();
					updateCart();
					googleCheckoutCompleteOrder();
				});
				$j('#paymentChoices').show();
				$j('#paymentChoiceGoogleRow').show();
			}
		}
		
		
		
		
		
		
		
		
		// Secret button for catching "enter/return"
		
		$j("#secret_finalize button").click(function(event){
			event.preventDefault();
			if(document.getElementById('creditCard').checked)
			{
				$j("#secret_finalize button").attr('disabled', 'disabled');
				setAddress();
				setPaymentInfo();
				updateCart();
				calculateShippingSync();
				var errors = validateAll();
				if(errors != null && errors.length > 0)
				{
					$j("#secret_finalize button").removeAttr('disabled');
					displayCartErrors(errors);
					pulseFirstEmptyInput();
				}
				else
				{
					completeOrder();
				}
			}
			if(document.getElementById('paypal').checked)
			{
				$j('#paypalCheckout').click();
			}
			if(document.getElementById('google').checked)
			{
				$j('#googleCheckout').click();
			}
		});
		
		
		
		
		
		
		
		
		// Click the 'change selection' link
		
		$j('#change_selection a').click(function(event){
			event.preventDefault();
			hideCartDetails();
			showAllProducts();
			unCheckAllProducts();
			$j('#product_table').show('fast');
			$j('#product_table td').each(function(){
				if($j(this).attr('class'))
				{
					$j(this).attr('class', 'price_col')
				}
			});
			$j('.checkout').hide('fast');
			scrollToProducts();
			clearItems();
		});
		
		
		
		
		
		
		
		
		// Setup the current state of the page based upon the cart contents
		
		styleCheckMarksForItemsInCart();
		
		if(cart.items.length > 0)
		{
			hideUncheckedProducts();
			displayCartDetails();
			calculateShipping();
			scrollToCheckout();
			pulseFirstEmptyInput();
			$j('#product_table').hide();
			$j('.checkout').show();
		}
		else
		{
			hideCartDetails();
		}
		
		
		hideShowBillingAddress();
	}
	catch(e)
	{
		handleError('load', e);
	}
	
	
	
	
	
	
	
	
	// Product square clicked
	
	squareClicked = function(itemId) {
		addItemToCart(itemId);
		displayCartDetails();
		$j('#product_table').hide('slow');
		$j('.checkout').show('fast');
		calculateShipping();
		scrollToCheckout();
	}
	
	
	
	
	
	
	
	
	// Trim
	
	function trim(str, chars)
	{
		try
		{
			return ltrim(rtrim(str, chars), chars);
		}
		catch(e)
		{
			handleError('trim()', e);
			return false;
		}
	}
	
	
	function ltrim(str, chars)
	{
		try
		{
			chars = chars || "\\s";
			return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
		}
		catch(e)
		{
			handleError('ltrim()', e);
			return false;
		}
	}
	
	
	function rtrim(str, chars)
	{
		try
		{
			chars = chars || "\\s";
			return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
		}
		catch(e)
		{
			handleError('rtrim()', e);
			return false;
		}
	}
	
	
	
	
	
	
	
	
	// Choose payment method
		
	function choosePaymentMethod()
	{
		try
		{
			$j('#paymentChoices input[type=radio]').each(function(){
				if($j(this).val() == 'creditCard' && this.checked)
				{
					$j('#payPalPaymentBlock').hide();
					$j('#googlePaymentBlock').hide();
					$j('#creditCardPaymentBlock').show('fast');
					if(cart.items.length > 0)
					{
						$j('#shipping_options').show('fast');
						$j('#checkout_total').show('fast');
						$j('#finalize_order').show('fast');
					}
				}
				
				if($j(this).val() == 'paypal' && this.checked)
				{
					$j('#creditCardPaymentBlock').hide();
					$j('#googlePaymentBlock').hide();
					$j('#shipping_options').hide();
					$j('#checkout_total').hide();
					$j('#finalize_order').hide();
					$j('#payPalPaymentBlock').show('fast');
				}
				
				if($j(this).val() == 'google' && this.checked)
				{
					$j('#creditCardPaymentBlock').hide();
					$j('#payPalPaymentBlock').hide();
					$j('#shipping_options').hide();
					$j('#checkout_total').hide();
					$j('#finalize_order').hide();
					$j('#googlePaymentBlock').show('fast');
				}
			});
		}
		catch(e)
		{
			handleError('choosePaymentMethod()', e);
		}
	}
	
	
	
	
	
	
	
	
	function updateStatesProvinces(country, id)
	{
		var stateProvinces = getStateProvinces(country);
		if(stateProvinces && stateProvinces.length > 0)
		{
			$j('#' + id).parent().html('<select id="' + id + '" name="' + id + '"></select>');
			$j('#' + id).html($j('#' + id).html() + '<option selected="selected"></option>\n');
			for(i = 0; i < stateProvinces.length; i ++)
			{
				$j('#' + id).html($j('#' + id).html() + '<option>' + String(stateProvinces[i]) + '</option>\n');
			}
		}
		else
		{
			$j('#' + id).parent().html('<input id="' + id + '" class="input_text" type="text" name="' + id + '" />');
		}
		$j('#' + id).blur(function(){
			updateShippingIfNeeded();
		});
	}
	
	
	
	
	
	
	
	
	// Check if item is in the cart
	
	function itemIsInCart(itemId)
	{
		try
		{
			if (itemId == null || cart.items == null)
			{
				return false;
			}
			var i;
			for (i = 0; i < cart.items.length; i++)
			{
				if (cart.items[i].itemId == itemId)
				{
					return true;
				}
			}
		}		
		catch(e)
		{
			handleError('rtrim()', e);
		}
		
		return false;
	}
	
	
	
	
	
	
	
	
	
	// Error handling
	
	function handleError(message, error)
	{
		try
		{
			var logMessage = '';
			if(message)
			{
				logMessage += message;
				logMessage += ':\n';
			}
			
			if(error)
			{
				logMessage += error;
				logMessage += '\nFile:';
				logMessage += error.fileName;
				logMessage += '\nLine:';
				logMessage += error.lineNumber;
			}
			logError(String(logMessage));
		}
		catch(e)
		{
			alert('There was a small error, please refresh your page.' + e);
		}
	}
	
	
	
	
	
	
	
	
	// Uncheck all products
	
	function unCheckAllProducts()
	{
		try
		{
			
			$j('.product_row_desc_row input[type=checkbox]').each(function(){
				$j(this)[0].checked = false;
				$j(this).parent('div').attr('class', 'large_check_off');
			});
			
			$j('#cart_contents').hide('fast');
		}
		catch(e)
		{
			handleError('unCheckAllProducts()', e);
		}
	}
	
	
	
	
	
	
	
	
	// Check all products that are in the cart
	
	function styleCheckMarksForItemsInCart()
	{
		try
		{
			$j('.product_row_desc_row input[type=checkbox]').each(function(){
				if(cart.items == null)
				{
					$j(this)[0].checked = false;
					$j(this).parent('div').attr('class', 'large_check_off');
				}
				else
				{
					if(itemIsInCart($j(this).val(), cart.items))
					{
						$j(this)[0].checked = true;
						$j(this).parent('div').attr('class', 'large_check_on');
					}
					else
					{
						$j(this)[0].checked = false;
						$j(this).parent('div').attr('class', 'large_check_off');
					}
				}
			});
		}
		catch(e)
		{
			handleError('styleCheckMarksForItemsInCart()', e);
		}
	}
	
	
	
	
	
	
	
	
	
	// Hide unchecked products
	
	function hideUncheckedProducts()
	{
		try
		{
			$j('.product_row_desc_row input[type=checkbox]').each(function(){
				if(this.checked == true)
				{
					$j(this).parent('div').attr('class', 'large_check_on');
				}
				else
				{
					$j(this).parent().parent().parent().hide('fast');
				}
			});
		}
		catch(e)
		{
			handleError('hideUncheckedProducts()', e);
		}
	}
	
	
	
	
	
	
	
	
	// Hide or show billing address depending on whether the checkbox is checked
	
	function hideShowBillingAddress()
	{
		try
		{
			if(document.getElementById('billingSameAsShipping').checked)
			{
				$j('#checkout_billing dl').hide();
			}
			else
			{
				$j('#checkout_billing dl').show();
			}
		}
		catch(e)
		{
			handleError('hideShowBillingAddress()', e);
		}
	}
	
	
	
	
	
	
	
	
	// Hide cart details
	
	function hideCartDetails()
	{
		try
		{
			$j('#change_selection').hide();
			$j('#checkout_total').hide('fast');
			$j('#shipping_options').hide('fast');
			$j('#cart_errors').hide('fast');
			$j('#other_payment_options').hide('fast');
			$j('#finalize_order').hide('fast');
			$j('#cart_contents').hide();
		}
		catch(e)
		{
			handleError('hideCartDetails()', e);
		}
	}
	
	
	
	
	
	
	
	
	// Hide cart details
	
	function displayCartDetails()
	{
		try
		{
			if(cart == null)
			{
				throw('Cart is null')
			}
			
			$j('#cart_contents').show();
			$j('#cart_contents tbody').html('\n');
			$j('#change_selection').show('fast');
			$j('#finalize_order').show('fast');
			
			if((cart.hasPayPal && cart.payPalCompatible) || (cart.hasGoogleCheckout && cart.googleCheckoutCompatible))
			{
				$j('#other_payment_options').show('fast');
			}
			
			for(i = 0; i < cart.items.length; i ++)
			{
				$j('#cart_contents tbody').html($j('#cart_contents tbody').html() + '<tr>' + '<td class="col_1">' + String(cart.items[i].quantity) + '</td>' + '<td class="col_2">' + String(cart.items[i].description) + '</td>' + '<td class="col_3">$' + String((cart.items[i].unitCost * cart.items[i].quantity).toFixed(2)) + '</td>' + '</tr>');
			}
		}
		catch(e)
		{
			handleError('displayCartDetails()', e);
		}
	}
	
	
	
	
	
	
	
	
	
	// Show all products
	
	function showAllProducts()
	{
		try
		{
			$j('.product_row_desc_row input[type=checkbox]').each(function(){
				$j(this).parent().parent().parent().show();
			});
		}
		catch(e)
		{
			handleError('showAllProducts()', e);
		}
	}
	
	
	
	
	
	
	
	
	
	// Scroll to checkout
	
	function scrollToCheckout()
	{
		$j('html,body').animate({scrollTop: $j('#cart_contents').offset().top - 10}, 750);
	}
	
	
	
	
	
	
	
	
	// Scroll to errors
	
	function scrollToErrors()
	{
		$j('html,body').animate({scrollTop: $j('#cart_errors').offset().top - 10}, 750);
	}
	
	
	
	
	
	
	
	
	// Pulse first empty input (except Address 2)
	
	function pulseFirstEmptyInput()
	{
		try
		{
			var pulsed = false;
			$j('.checkout :input[type!=radio]').each(function(){
				if($j(this).val() == false && ($j(this).attr('name') != 'shippingAddress2'))
				{
					if(pulsed == false)
					{
						$j(this).focus();
						$j(this).animate( { backgroundColor:"yellow" } , 250 )
						.animate( { backgroundColor:"lightyellow" }, 2000);
						$j(this).focus();
						$j(this).blur(function(){
							$j(this).css('background', '#F5F5F5');
						});
						pulsed = true;
					}
				}
			});
		}
		catch(e)
		{
			handleError('pulseFirstEmptyInput()', e);
		}
	}
	
	
	
	
	
	
	
	
	
	// Scroll to products
	
	function scrollToProducts()
	{
		$j('html,body').animate({scrollTop: $j('#cart_wrapper').offset().top}, 750);
	}
	
	
	
	
	
	
	
	
	// Add item to cart
	
	function addItemToCart(itemId)
	{
		try
		{
			var itemToAdd = new Array();
			itemToAdd[0] = {'itemId': itemId, 'quantity': 1};
			
			var errors = updateItems(itemToAdd);
			if(errors != null && errors.length > 0)
			{
				displayCartErrors(errors);
			}
		}
		catch(e)
		{
			handleError('addItemToCart()', e);
		}
	}
	
	
	
	
	
	
	
	
	
	// Set address within cart object
	
	function setAddress()
	{
		try
		{
			if(cart == null)
			{
				throw('Cart is null')
			}
			
			
			var shippingState		=	$j('#shippingState').val();
			var shippingCountry	=	$j('#shippingCountry').val();
			cart.shipToState		=	shippingState;
			cart.shipToCountry	=	shippingCountry;
			
			cart.shipToPhone		=	$j('#shippingDayPhone').val();
			cart.email			=	$j('#email').val();
			cart.shipToAddress1	=	$j('#shippingAddress1').val();
			cart.shipToAddress2	=	$j('#shippingAddress2').val();
			cart.shipToPostalCode	=	$j('#shippingPostalCode').val();
			cart.shipToCity		=	$j('#shippingCity').val();
			cart.shipToFirstName	=	$j('#shippingFirstName').val();
			cart.shipToLastName	=	$j('#shippingLastName').val();
			
			if($j('input[name=billingSameAsShipping]')[0].checked)
			{
				cart.billToState		=	cart.shipToState;
				cart.billToCountry	=	cart.shipToCountry;
				cart.billToDayPhone	=	cart.shipToPhone;
				cart.billToAddress1	=	cart.shipToAddress1;
				cart.billToAddress2	=	cart.shipToAddress2;
				cart.billToPostalCode	=	cart.shipToPostalCode;
				cart.billToCity		=	cart.shipToCity;
				cart.billToFirstName	=	cart.shipToFirstName;
				cart.billToLastName	=	cart.shipToLastName;
			}
			else
			{
				var billingState		=	$j('#billingState').val();
				var billingCountry	=	$j('#billingCountry').val();
				cart.billToState		=	billingState;
				cart.billToCountry	=	billingCountry;
				
				cart.billToDayPhone	=	$j('#billingDayPhone').val();
				cart.billToAddress1	=	$j('#billingAddress1').val();
				cart.billToAddress2	=	$j('#billingAddress2').val();
				cart.billToPostalCode	=	$j('#billingZip').val();
				cart.billToCity		=	$j('#billingCity').val();
				cart.billToFirstName	=	$j('#billingFirstName').val();
				cart.billToLastName	=	$j('#billingLastName').val();
			}
		}
		catch(e)
		{
			handleError('setAddress()', e);
		}
	}
	
	
	
	
	
	
	
	
	// Input address values from cart
	
	function inputAddressValues()
	{
		try
		{
			$j('#shippingFirstName').val(cart.shipToFirstName);
			$j('#shippingLastName').val(cart.shipToLastName);
			$j('#email').val(cart.email);
			$j('#shippingCountry').val(cart.shipToCountry);
			$j('#shippingState').val(cart.shipToState);
			$j('#shippingDayPhone').val(cart.shipToPhone);
			$j('#shippingAddress1').val(cart.shipToAddress1);
			$j('#shippingAddress2').val(cart.shipToAddress2);
			$j('#shippingPostalCode').val(cart.shipToPostalCode);
			$j('#shippingCity').val(cart.shipToCity);
			
			$j('#billingFirstName').val(cart.billToFirstName);
			$j('#billingLastName').val(cart.billToLastName);
			$j('#billingCountry').val(cart.billToCountry);
			$j('#billingState').val(cart.billToState);
			$j('#billingDayPhone').val(cart.billToDayPhone);
			$j('#billingAddress1').val(cart.billToAddress1);
			$j('#billingAddress2').val(cart.billToAddress2);
			$j('#billingZip').val(cart.billToPostalCode);
			$j('#billingCity').val(cart.billToCity);
			
			$j('#creditCardType').val(cart.creditCardType);
			$j('#creditCardNumber').val(cart.creditCardNumber);
			$j('#creditCardExpMonth').val(cart.creditCardExpirationMonth);
			$j('#creditCardExpYear').val(cart.creditCardExpirationYear);
			$j('#creditCardVerificationNumber').val(cart.creditCardVerificationNumber);
			
			if(cart.billToAddress1 != cart.shipToAddress1 || cart.shipToFirstName != cart.billToFirstName || cart.shipToPostalCode != cart.billToPostalCode)
			{
				if(document.getElementById('billingSameAsShipping').checked == true)
				{
					document.getElementById('billingSameAsShipping').click();
				}
			}
			
		}
		catch(e)
		{
			handleError('inputAddressValues()', e);
		}
	}
	
	
	
	
	
	
	
	
	
	// Set payment info
	
	function setPaymentInfo()
	{
		try
		{
			if(cart == null)
			{
				throw('Cart is null')
			}
			
			cart.paymentMethod = PAYMENT_METHOD_CREDIT_CARD;
			cart.creditCardType					=	$j('#creditCardType').val();
			cart.creditCardNumber				=	$j('#creditCardNumber').val();
			var creditCardExpirationMonth		=	$j('#creditCardExpMonth').val();
			cart.creditCardExpirationMonth		=	parseInt(creditCardExpirationMonth);
			var creditCardExpirationYear		=	$j('#creditCardExpYear').val();
			cart.creditCardExpirationYear		=	parseInt(creditCardExpirationYear);
			cart.creditCardVerificationNumber	=	$j('#creditCardVerificationNumber').val();
		}
		catch(e)
		{
			handleError('setPaymentInfo()', e);
		}
	}
	
	
	
	
	
	
	
	
	// Update shipping if needed
	
	function updateShippingIfNeeded()
	{
		try
		{
			if(cart == null)
			{
				throw('Cart is null');
			}
			
			var currentShipToState		=	$j('#shippingState').val();
			var currentShipToCountry	=	$j('#shippingCountry').val();
			
			if(trim(cart.shipToAddress1.toString().toUpperCase()) == trim($j('#shippingAddress1').val().toString().toUpperCase()) && trim(cart.shipToAddress2.toString().toUpperCase()) == trim($j('#shippingAddress2').val().toString().toUpperCase())  && trim(cart.shipToCity.toString().toUpperCase()) == trim($j('#shippingCity').val().toString().toUpperCase()) && trim(cart.shipToPostalCode.toString().toUpperCase()) == trim($j('#shippingPostalCode').val().toString().toUpperCase()) && trim(cart.shipToState.toString().toUpperCase()) == trim(currentShipToState.toString().toUpperCase()) && trim(cart.shipToCountry.toString().toUpperCase()) == trim(currentShipToCountry.toString().toUpperCase()))
			{
				return;
			}
			else if(trim($j('#shippingAddress1').val().toString().toUpperCase())  && trim($j('#shippingCity').val().toString().toUpperCase()) && trim($j('#shippingPostalCode').val().toString().toUpperCase()) && trim(currentShipToState.toString().toUpperCase()) && trim(currentShipToCountry.toString().toUpperCase()))
			{
				setAddress();
				updateCart();
				calculateShipping();
			}
			else
			{
				return;
			}
		}
		catch(e)
		{
			handleError('updateShippingIfNeeded()', e);
		}
	}
	
	
	
	
	
	
	
	
	// Handoff for order completion
	
	function completeOrder()
	{
		try
		{
			if(secureHostName)
			{
				var handoffResult = checkoutHandoffOnCustomSSL(secureHostName, returnOnErrorUrl, "error");
			}
			else
			{
				var handoffResult = checkoutHandoff(returnOnErrorUrl, "error");
			}
			
			if(handoffResult.errors != null && handoffResult.errors.length == 0)
			{
				window.location = handoffResult.redirectToUrl;
			}
			else
			{
				for(i = 0; i < handoffResult.errors.length; i ++)
				{
					alert('Error: ' + handoffResult.errors[i]);
				}
			}
		}
		catch(e)
		{
			handleError('completeOrder()', e);
		}
	}
	
	
	
	
	
	
	
	
	// Paypal complete order
	
	function paypalCompleteOrder()
	{
		try
		{
			$j('#paypalCheckout').removeAttr('disabled');
			if(secureHostName)
			{
				var handoffResult = paypalHandoffOnCustomSSL(secureHostName, returnOnErrorUrl, "error");
			}
			else
			{
				var handoffResult = paypalHandoff(returnOnErrorUrl, "error");
			}
			
			if(handoffResult.errors != null && handoffResult.errors.length == 0)
			{
				window.location = handoffResult.redirectToUrl;
			}
			else
			{
				displayCartErrors(handoffResult.errors);
			}
		}
		catch(e)
		{
			handleError('paypalCompleteOrder()', e);
		}
	}
	
	
	
	
	
	
	
	
	// Display errors from query string
	
	function displayQueryErrors()
	{
		try
		{
			var errors = getParameterValues("error");
			
			if(errors != null && errors.length > 0)
			{
				displayCartErrors(errors);
			}		
		}
		catch(e)
		{
			handleError('displayQueryErrors()', e);
		}
	}
	
	
	
	
	
	
	
	
	// Google complete order
	
	function googleCheckoutCompleteOrder()
	{
		try
		{
			$j('#googleCheckout').removeAttr('disabled');
			if(secureHostName)
			{
				var handoffResult = googleCheckoutHandoffOnCustomSSL(secureHostName, returnOnErrorUrl, "error");
			}
			else
			{
				var handoffResult = googleCheckoutHandoff(returnOnErrorUrl, "error");
			}
			
			if(handoffResult.errors != null && handoffResult.errors.length == 0)
			{
				window.location = handoffResult.redirectToUrl;
			}
			else
			{
				displayCartErrors(handoffResult.errors);
			}
		}
		catch(e)
		{
			handleError('googleCheckoutCompleteOrder()', e);
		}
	}
	
	
	
	
	
	
	
	
	// Display validation errors
		
	function displayCartErrors(errors)
	{
		try
		{
			$j('#cart_errors').show('fast');
			scrollToErrors();
			$j('#cart_errors ul').html('\n');
			for(i = 0; i < errors.length; i ++)
			{
				$j('#cart_errors ul').html($j('#cart_errors ul').html() + '<li>' + String(errors[i]) + '</li>' + '\n');
			}
		}
		catch(e)
		{
			handleError('displayCartErrors()', e);
		}
	}
	
	
	
	
	
	
	
	
	
	// Display cart totals
	
	function displayCartTotals()
	{
		try
		{
			var subtotal		=	'$' + String(cart.subtotal.toFixed(2));
			var shippingTotal		=	'$' + String(cart.shippingHandling.toFixed(2));
			var taxTotal		=	'$' + String(cart.tax.toFixed(2));
			var total			=	'$' + String(cart.total.toFixed(2));
			if(cart.buysafeBondCost)
			{
				var buySafeTotal		=	'$' + String(cart.buysafeBondCost.toFixed(2));
			}
			
			$j('#total_subtotal').text(subtotal);
			$j('#total_shipping_cost').text(shippingTotal);
			$j('#total_tax').text(taxTotal);
			$j('#total_total').text(total);
			
			if(cart.buysafeBondWanted)
			{
				$j('#total_buysafe').text(buySafeTotal);
			}
			else
			{
				$j('#total_buysafe').text('\n');
			}
			
			
			if(cart.buysafeBondAvailable)
			{
				displayBuySafe();
			}
			
			if(cart.total > 0)
			{
				$j('#checkout_total').show('fast');
			}
			
			$j('#buySafeLink a').text(cart.buysafeCartDisplayText);
			$j('#buySafeLink a').attr('href', cart.buysafeCartDisplayUrl);
		}
		catch(e)
		{
			handleError('displayCartTotals()', e);
		}
	}
	
	
	
	
	
	$j('#buySafeLink a').click(function(event){
		event.preventDefault();
		window.open($j(this).attr('href'));
	});
	
	
	
	
	
	
	
	
	
	// Display shipping estimates
	
	function displayShippingOptions(shippingEstimates)
	{
		try
		{
			if(cart == null)
			{
				throw('Cart is null')
			}
			
			$j('#shipping_options_inner').html('\n');
			
			var checkedAttribute = null;
			
			if(lastShippingEstimates != null && lastShippingEstimates.length > 0)
			{
				for (var i = 0; i < shippingEstimates.length; i++)
				{
					checkedAttribute = ' ';
					
					if(cart.shippingMethod)
					{
						if(cart.shippingMethod == shippingEstimates[i].name)
						{
							checkedAttribute = 'checked="checked"';
						}
					}
					else
					{
						if(i == 0)
						{
							checkedAttribute = 'checked="checked"';
						}
					}
					
					$j('#shipping_options_inner').html($j('#shipping_options_inner').html() + '<div class="shipping_row">\n<div class="shipping_input_col">' + '<input ' + checkedAttribute + ' id="num' + i + '" type="radio" name="shippingRadio" value="' + String(shippingEstimates[i].name) + '" /></div><!--/shipping_input_col-->\n<div class="shipping_label_col">' + '<label for="num' + i + '">' + String(shippingEstimates[i].displayName) + '</label><span>$' + String(shippingEstimates[i].cost.toFixed(2)) + '</span></div><!--/shipping_label_col-->' + '</div>');
				}
			}
			else
			{
				$j('#shipping_options_inner').html($j('#shipping_options_inner').html() + '<div class="shipping_row"></div>No shipping estimates found for your address.<!--/shipping_row-->');
			}
			
			$j('input[name=shippingRadio]').click(function(){
				selectShipping($j(this).val());
			});
		}
		catch(e)
		{
			handleError('displayShippingOptions()', e);
		}
	}
	
	
	
	
	
	
	
	
	// BuySafe Click
	
	buySAFEOnClick = function()
	{
		try
		{
			cart.buysafeBondWanted = !cart.buysafeBondWanted;
			updateCart();
			displayCartTotals();
		}
		catch(e)
		{
			handleError('buySAFEOnClick()', e);
		}
	}
	
	
	
	
	
	
	
	
	// Display BuySafe
	
	function displayBuySafe()
	{
		try
		{
			if(cart == null)
			{
				throw('Cart is null')
			}
			
			if(WriteBuySafeButton)
			{
				//alert("Evaluating " + cart.buysafeBondingSignalJavascript);
				eval(cart.buysafeBondingSignalJavascript);
			}
			
		}
		catch(e)
		{
			handleError('displayBuySafe()', e);
		}
	}
	
	
	
	
	
	
	
	
	// Set shipping method and cost
	
	function calculateShipping()
	{
		try
		{
			if(cart == null)
			{
				cart = getCartInstance();
			}
			
			$j('#shipping_options').show('fast');
			$j('#shipping_options_inner').html('Calculating&hellip;');
			
			var shippingEstimates = estimateShipping();
			// We're going to fire off the estimate shipping asynchronously
			estimateShipping({'async': true, 'onComplete': function(shippingEstimates){
					lastShippingEstimates = shippingEstimates;
					
					if(lastShippingEstimates != null && lastShippingEstimates.length > 0)
					{
						if(cart.shippingMethod && cart.shippingMethod != "") {
							for (var i = 0; i < shippingEstimates.length; i++)
							{
								if(shippingEstimates[i].name == cart.shippingMethod)
								{
									cart.shippingHandling = shippingEstimates[i].cost;
								}
							}
						}
						else
						{
							cart.shippingMethod = shippingEstimates[0].name;
							cart.shippingHandling = shippingEstimates[0].cost;
						}
					}
					
					updateCart();
					displayShippingOptions(shippingEstimates);
					displayCartTotals();
				}
			});
		}
		catch(e)
		{
			handleError('calculateShipping()', e);
		}
	}

	// Set shipping method and cost
	function selectShipping(methodName)
	{
		try
		{
			if(cart == null)
			{
				cart = getCartInstance();
			}
			if(cart.items.length == 0)
			{
				return;
			}

			
			if(methodName || cart.shippingMethod)
			{
				if(methodName)
				{
					cart.shippingMethod = methodName;
				}
				for (var i = 0; i < lastShippingEstimates.length; i++)
				{
					if(lastShippingEstimates[i].name == cart.shippingMethod)
					{
						cart.shippingHandling = lastShippingEstimates[i].cost;
					}
				}
			}
			
			updateCart();
			displayCartTotals();
		}
		catch(e)
		{
			handleError('selectShipping()', e);
		}
	}
	
	// Set shipping method and cost
	function calculateShippingSync()
	{
		try
		{
			if(cart == null)
			{
				cart = getCartInstance();
			}
			if(cart.items.length == 0)
			{
				return;
			}
			
			var shippingEstimates = estimateShipping();
			
			if(cart.shippingMethod != null && cart.shippingMethod != "")
			{
				for (var i = 0; i < shippingEstimates.length; i++)
				{
					if(shippingEstimates[i].name == cart.shippingMethod)
					{
						cart.shippingHandling = shippingEstimates[i].cost;
					}
				}
			}
			else if(shippingEstimates.length > 0) 
			{
				cart.shippingMethod = shippingEstimates[0].name;
				cart.shippingHandling = shippingEstimates[0].cost;
			}
			
			updateCart();
			displayCartTotals();
		}
		catch(e)
		{
			handleError('calculateShippingSync()', e);
		}
	}
	
	
	
	
	
	
	
	
	// Remove shipping
	
	function removeShipping()
	{
		try
		{
			cart.shippingMethod = ' ';
			cart.shippingHandling = 0;
			updateCart();
		}
		catch(e)
		{
			handleError('removeShipping()', e);
		}
	}



	// Add item/items to cart
	
	function addItemsToCart(itemId, theRebate)
	{
		try
		{
			
			$j('[name=ADD]').each(function(){
				if(this.checked)
				{
				addItemToCart($j(this).val());
				displayCartDetails();
				calculateShipping();
				scrollToCheckout();
				}
				
			});
			
		}
		catch(e)
		{
			handleError('addItemsToCart()', e);
		}
	}
	




});
