var loc = location.href;
var href;
href = loc.split('/');
href = href[0]+'//'+href[2]+'/';
function fixInputBox(i,fixedPlace)
{
	i.value = Math.abs(i.value*1);
	i.value = (i.value*1).toFixed(fixedPlace);
	if(i.value == "NaN")
	{
		i.value = "0";
	}
	return i;
}


var promo_cto = undefined;
var promo_code_request;
function checkPromoCode(ele,applyPopUpSelection)
{
	if(promo_code_request)promo_code_request.cancel();
	if(promo_cto)clearTimeout(promo_cto);

	promo_cto = setTimeout(function(){
		var promoCode = escape(ele.value);

		if(ele != $('shopping_cart_promo_code'))
		{
			try
			{
				$('shopping_cart_promo_code'). value = promoCode;
			}
			catch(err){}
		}
		else
		{
			$('mini_cart_promoCode').value = promoCode;
		}
		promo_code_request = new Request({
			url: href+'p_include/ajax_func.html',
			method: 'post',
			onComplete: function(response_text) {

				if(promo_cto)clearTimeout(promo_cto);

				try
				{
					if(JSON.decode(response_text).success)
					{
						evaluateGiftCertificatePromotionCodePopUp();
					}
				}
				catch(err){}
					updateShoppingCartValues('',applyPopUpSelection);
			}
		}).send('func=checkPromoCode&promoCode='+escape(promoCode));

	}, 500);


}


var clear_timeout = undefined;
function adjustQuantity(my_event, my_element, product_id, bundle_id, override_qty)
{
	if(my_element.value!='')fixInputBox(my_element,0);
	var new_qty;
	if(override_qty){
		new_qty = override_qty;
	}
	else{
		new_qty = my_element.value;
	}
	
	if(my_element != $('shopping_cart_product_qty_'+product_id+'_'+bundle_id))
	{
		try
		{
			$('shopping_cart_product_qty_'+product_id+'_'+bundle_id).value = new_qty;

		}
		catch(err){}
	}
	//else
	{
		$('mini_cart_product_qty_'+product_id+'_'+bundle_id).value = new_qty;
	}

	try
	{
		var bundle_products = JSON.decode($('shopping_cart_bundle_products').value);

		for(var i=0; i< bundle_products.length; i++)
		{
			for(var k=0; k < bundle_products[i].length; k++)
			{
				if(bundle_id ==bundle_products[i][k].bundle_id)
				$('product_bundle_qty_'+bundle_products[i][k].product_id+'_'+bundle_products[i][k].bundle_id).innerHTML = ((bundle_products[i][k].qty *1 ) * (new_qty * 1));
			}
		}
	}
	catch(err) {}



	if(new_qty ==0)
	{
		$('mini_cart_product_'+product_id+'_'+bundle_id).className='absentProduct';

		try
		{
			$('shopping_cart_product_'+product_id+'_'+bundle_id).addClass("absentProduct");
		}
		catch(err){}
	}

	else
	{
		$('mini_cart_product_'+product_id+'_'+bundle_id).className='';

		try
		{
			$('shopping_cart_product_'+product_id+'_'+bundle_id).removeClass("absentProduct");
		}
		catch(err){}
	}
	if(clear_timeout)clearTimeout(clear_timeout);

	//if(((my_event.keyCode>=48 && my_event.keyCode<=57) || (my_event.keyCode>=96 && my_event.keyCode<=105) || (my_event.keyCode==8 && my_element.value!=0)))//the value was changed AND either a number was pressed, or backspace was pressed while the field was NOT 0
	//{
	clear_timeout = setTimeout(function(){
		var qty = new_qty;
		new Request({
			url: href+'p_include/ajax_func.html',
			method: 'post',
			onComplete: function(response) {

				var return_value = JSON.decode(response);

				$('mini_cart_prodTotal_'+product_id+'_'+bundle_id).innerHTML = return_value.productSubTotal;

				try
				{
					$('shopping_cart_prodTotal_'+product_id+'_'+bundle_id).innerHTML = return_value.productSubTotal;
				}
				catch(err){}
				updateShoppingCartValues();

				if(clear_timeout)clearTimeout(clear_timeout);
			}
		}).send('func=adjustQuantity&product_id='+product_id+'&qty='+qty+'&bundle_id='+bundle_id);
	}, 250);
	//}
}

function removeProduct(product_id,bundle_id)
{
	//main cart removal
	try
	{
		var row_index = $('shopping_cart_product_'+product_id+"_"+bundle_id).rowIndex;
		$('shopping_cart_product_table').deleteRow(row_index);


		removeProductFromStoredArray(product_id);
		resetGiftCartIfPurchasingGiftCard();
		validateGiftCertPaymentAmount();
		figureOutCreditCardPaymentAmount();
	}
	catch(err){}

	$('span_mini_cart_product_'+product_id+"_"+bundle_id).dispose();

	new Request({
		url: href+'p_include/ajax_func.html',
		method: 'post',
		onComplete: function(response) {
			adjustProductHeight();
			//var json_array = JSON.decode(response);
			checkPromoCode($('mini_cart_promoCode'));

			if(response == "0")
			{
				if(window.location.toString().indexOf("checkout.html") != -1)
				{

					window.location = "checkout.html";
				}
			}


		}
	}).send('func=removeProduct&product_id='+product_id+"&bundle_id="+bundle_id);
}
function addProduct(product_id,bundle_id)
{
	if(!bundle_id || bundle_id==null || bundle_id==undefined)bundle_id=0;
	else if(bundle_id!=0)product_id='';

	var productAlreadyInCart = $('mini_cart_product_'+product_id+'_'+bundle_id)?true:false;
	//alert(productAlreadyInCart);
	allowCartToClose = false;

	new Request({
		url: href+'p_include/ajax_func.html',
		method: 'post',
		onComplete: function(response) {
			var new_node;
			new_node = document.createElement('span');
			new_node.id = 'span_mini_cart_product_'+product_id+'_'+bundle_id;
			new_node.innerHTML = response;
			if(!productAlreadyInCart)
			{
				var first_node = $('miniCartProducts').firstChild;
				$('miniCartProducts').insertBefore(new_node,first_node);// = (response + $('miniCartProducts').innerHTML);
			}
			else
			{
				$('miniCartProducts').replaceChild(new_node,$('span_mini_cart_product_'+product_id+'_'+bundle_id));
			}
			adjustProductHeight();
			openMiniCart();
			checkPromoCode($('mini_cart_promoCode'));
			allowCartToClose = true;
			if(productAlreadyInCart)$('productsInCart').scrollTop=$('mini_cart_product_'+product_id+'_'+bundle_id).offsetTop;
		}
	}).send('func=addProduct&product_id='+product_id+"&bundle_id="+bundle_id);
}
function addProductWithOptions(ele)
{
	var bundle_id = 0;
	var product_id = ele.value;
	addProduct(product_id, bundle_id);
}
function addRecurringProduct(product_id, bundle_id)
{
	addProduct(product_id, bundle_id);
	var qty = $('recurringQty').value;
	var frequency = $('frequency').value;
	if(!bundle_id || bundle_id=='')bundle_id=0;
	new Request({
		method: 'post',
		url: href+"p_include/ajax_func.html",
		onComplete : function()
		{
			Slider.close();			
			adjustQuantity('', $('mini_cart_product_qty_'+product_id+'_'+bundle_id), product_id, bundle_id, qty);
			$('mini_cart_recurr_notice_'+product_id+'_'+bundle_id).set('html','AUTOMATIC SHIPMENT');
			$('recurringDiscountMiniCart').style.display = '';
		}
	}).send('func=addRecurringProduct&product_id='+product_id+'&bundle_id='+bundle_id+'&qty='+qty+'&frequency='+frequency);	
}
function setPromotionCodeAndAddProduct(product_id,promotionCode)
{

	new Request({
		method: 'post',
		url: href+"p_include/checkout_ajax_func.html",
		onComplete : function()
		{
			$('mini_cart_promoCode').value=promotionCode;
			addProduct(product_id,0);
		}
	}).send('func=setPromotionCode&promotionCode='+promotionCode);
}

var shipping_cto = undefined;
function updateShippingOptions()
{
	if(shipping_cto)clearTimeout(shipping_cto);
	shipping_cto = setTimeout(function(){
		updateShoppingCartValues();
		if(shipping_cto)clearTimeout(shipping_cto);

	}, 400);
}
function updateShippingType(ele)
{
	var price, id, name, carrier;
	if(ele.value=="NULL" || ele.value=="0")
	{
		price = 0;
		id = '';
		name='';
		carrier='';
	}
	else
	{
		var values = ele.value.split('|');
		price = values[1];
		id = values[0];
		name = values[2];
		carrier = values[3];
	}
	new Request({
		url: href+'p_include/ajax_func.html',
		method: 'post',
		onComplete: function(response) {
			updateShoppingCartValues();
		}
	}).send('func=updateShippingType&price='+price+'&id='+id+'&name='+name+'&carrier='+carrier);
}
var update_values_request;
function updateShoppingCartValues(clearZip,applyPopUpSelection)
{
	if(update_values_request)update_values_request.cancel();
	if(clearZip && clearZip==1)$('zipCode').value='';
	var on_checkout_page;
	if($('shopping_cart_shippingDropDown'))on_checkout_page = true;
	else on_checkout_page = false;
	update_values_request = new Request({
		url: href+'p_include/ajax_func.html',
		method: 'post',
		onComplete: function(response) {
			var values = JSON.decode(response);
			//alert(href);
			if(on_checkout_page)
			{
				$('shopping_cart_subTotal').innerHTML = parseFloat(values['subTotal']).toFixed(2);
				$('shopping_cart_grand_total').innerHTML = parseFloat(values['grandTotal']).toFixed(2);
				$('shopping_cart_shippingDropDown').innerHTML = values['shippingDrowDown'];
				if(values['discountIsRecurring']==1)
				{
					$('shopping_cart_recurring_orders_discount').innerHTML = parseFloat(values['promoCodeDiscount']).toFixed(2);
					$('shopping_cart_promo_discount').innerHTML = parseFloat('0.00').toFixed(2);
					$('biggerCouponThanRecurringMessage').innerHTML='';
					if($('shopping_cart_promo_code').value != '' && (values['promotionCodeShippingDiscount']*1) == 0 && values['promoCodeDiscount'] > 0)
						$('biggerRecurringThanCouponMessage').innerHTML='<br>The automatic shipment discount has been applied because it is either greater than or equal to your coupon code discount.';
					else $('biggerRecurringThanCouponMessage').innerHTML='';
				}
				else
				{
					$('biggerRecurringThanCouponMessage').innerHTML='';
					$('shopping_cart_promo_discount').innerHTML = parseFloat(values['promoCodeDiscount']).toFixed(2);
					$('shopping_cart_recurring_orders_discount').innerHTML = parseFloat('0.00').toFixed(2);
					if(values['recurringProductsInCart']==1 && values['promoCodeDiscount'] > 0)
						$('biggerCouponThanRecurringMessage').innerHTML='<br>Your coupon code gives you a greater discount than the automatic shipment discount.';
					else $('biggerCouponThanRecurringMessage').innerHTML='';
				}
				$('shopping_cart_shippingAmount').innerHTML = parseFloat(values['shippingAmount']).toFixed(2);
				$('shopping_cart_tax_amount').innerHTML =  parseFloat(values['tax']).toFixed(2);
				if((((values['promoCodeDiscount'] *1) > 0 && values['discountIsRecurring']==0) || (values['promotionCodeShippingDiscount']*1)>0))
				{
					$('shopping_cart_promo_image').src=href+'p_images/positivePromoCodeIndicator.jpg';
				}
				else
				{
					$('shopping_cart_promo_image').src=href+'p_images/pendingPromoCodeIndicator.jpg';
				}

				validateGiftCertPaymentAmount(0,1);
				figureOutCreditCardPaymentAmount();
				$('countryDD').value = values['country'];
			}
			$('mini_cart_orderSubTotal').value = '$ '+parseFloat(values['subTotal']).toFixed(2);
			$('mini_cart_orderGrandTotal').value = '$ '+parseFloat(values['grandTotal']).toFixed(2);
			$('mini_cart_shippingDropDown').innerHTML =  values['shippingDrowDown'];
			$('mini_cart_promoCodeDiscount').value =  '- $ '+parseFloat(values['promoCodeDiscount']).toFixed(2);
			$('mini_cart_tax_amount').value =  '$ '+parseFloat(values['tax']).toFixed(2);
			var freeShippingAmount = values['subTotal']-values['promoCodeDiscount'];
			var shippingNotificationLabel = (values['country'].toUpperCase()=='UNITED STATES')?'FREE':'DISCOUNTED';
			if(freeShippingAmount>49)
			{
				$('miniCartShippingHeader').innerHTML='CONGRATULATIONS!';
				$('miniCartShippingText').innerHTML='Your order qualifies for <strong>'+shippingNotificationLabel+' SHIPPING</strong>';
			}
			else
			{
				$('miniCartShippingHeader').innerHTML='BEFORE YOU CHECKOUT!';
				$('miniCartShippingText').innerHTML='Qualify for <strong>'+shippingNotificationLabel+' SHIPPING</strong> if you add only <span class="remainingFreeShippingBalance">$'+(49-1*freeShippingAmount).toFixed(2)+'</span> to your order.';
			}
			var label='';
			if(values['productQty']>1 || values['productQty']==0)
			{
				label = ' ITEMS';
			}
			else
			{
				label = ' ITEM';
			}

			$('headerNumProducts').innerHTML = values['productQty'] + label;
			$('headerGrandTotal').innerHTML = parseFloat(values['grandTotal']).toFixed(2);
			if(values['discountIsRecurring']==1)
			{
				$('mini_cart_recurring_orders_discount').value =  '- $ '+parseFloat(values['promoCodeDiscount']).toFixed(2);
				$('mini_cart_promoCodeDiscount').value = '- $ '+parseFloat('0.00').toFixed(2);
			}
			else
			{
				$('mini_cart_promoCodeDiscount').value = '- $ '+parseFloat(values['promoCodeDiscount']).toFixed(2);
				$('mini_cart_recurring_orders_discount').value =  '- $ '+parseFloat('0.00').toFixed(2);
			}
			if((((values['promoCodeDiscount'] *1) > 0 && values['discountIsRecurring']==0) || (values['promotionCodeShippingDiscount']*1)>0))
			{
				$('mini_cart_promoCodeImg').src=href+'p_images/positivePromoCodeIndicator.jpg';
			}
			else
			{
				$('mini_cart_promoCodeImg').src=href+'p_images/pendingPromoCodeIndicator.jpg';
			}
			//alert(values['displayEmptyMessage']);
			if(values['productQty']==0 && values['displayEmptyMessage']=='1')
			{
				$('emptyCartMessage').innerHTML = ' You currently have no items in your cart. ';
			}
			else
			{
				$('emptyCartMessage').innerHTML = '';
			}
			if(applyPopUpSelection)applyGiftCertificatesFromPopUp();
		}
	}).send('func=updateShoppingCartValues&on_checkout_page='+on_checkout_page+'&zipCode='+$('zipCode').value+'&country='+$('countryDD').value);
}

function acceptTOS(ele)
{
	var accepted = ele.checked;
	new Request({
		url : 'p_include/ajax_func.html',
		method : 'post',
		onComplete:function(response){
			
		}
	}).send('func=acceptTOS&accepted='+accepted);
}