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)
{
	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
				{
					
					updateBingCashBack();
					if(JSON.decode(response_text).success)
					{
						evaluateGiftCertificatePromotionCodePopUp();
					}
				}
				catch(err){}
					updateShoppingCartValues('',true);
				
			}
		}).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;
			
			//billMeLater_promotion_checkbox
			if(($('shopping_cart_credit_card_total').innerHTML * 1) >= 250)
			{
				$('billMeLater_promotion_checkbox').disabled = false;
			}
			else
			{
				$('billMeLater_promotion_checkbox').disabled = true;
				$('billMeLater_promotion_checkbox').checked = false;
			}	

		}
		catch(err){}
	}
	//else
	{
		try
		{
			$('shopping_cart_product_qty_'+product_id+'_'+bundle_id).value = new_qty;
		}
		catch(err){}
		$('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");
			$('product_warnings_'+product_id+'_'+bundle_id).set('html','');
		}
		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);
				
				if(return_value.changedQty==1)
				{
					if(return_value.message)
					{
						alert(return_value.message);
					}
					adjustQuantity(null, my_element, product_id, bundle_id, return_value.qty);
					return;
				}

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

				try
				{
					$('shopping_cart_prodTotal_'+product_id+'_'+bundle_id).innerHTML = return_value.productSubTotal;
					updateBingCashBack();
				}
				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',
		evalScripts:true,
		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,qty)
{
	if(!qty)qty=1;
	qty = Math.abs(qty);
	
	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',
		evalScripts:true,
		onComplete: function(response) {
			response = JSON.decode(response);
			var new_node;
			new_node = document.createElement('span');
			new_node.id = 'span_mini_cart_product_'+product_id+'_'+bundle_id;
			new_node.innerHTML = response.html;
			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;
			if(response.message)
			{
				alert(response.message);
			}
		}
	}).send('func=addProduct&product_id='+product_id+"&bundle_id="+bundle_id+'&qty='+qty);
}
function addProductWithOptions(ele,qty)
{
	var bundle_id = 0;
	var product_id = ele.value;
	addProduct(product_id, bundle_id,qty);
}
function addRecurringProduct(product_id, bundle_id)
{
	var qty = $('recurringQty').value;
	var frequency = $('frequency').value;
	if(frequency == 0)
	{
		showPopUp('This product cannot be added to your car as "automatic shipment" because you have not selected how often you would like to receive the product.\n\nPlease select a frequency to add your product to the cart.');
	}
	else
	{	
		addProduct(product_id, bundle_id,1);
		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 addSubscriptionProduct(product_id, bundle_id)
{
	var qty = $('subscriptionQty').value;
	addProduct(product_id, bundle_id,1);
	if(!bundle_id || bundle_id=='')bundle_id=0;
	new Request({
		method: 'post',
		url: href+"p_include/ajax_func.html",
		onComplete : function()
		{
			Subscriptions.close();			
			adjustQuantity('', $('mini_cart_product_qty_'+product_id+'_'+bundle_id), product_id, bundle_id, qty);
			$('mini_cart_subscribe_notice_'+product_id+'_'+bundle_id).set('html','SUBSCRIPTION');
		}
	}).send('func=addSubscriptionProduct&product_id='+product_id+'&bundle_id='+bundle_id+'&qty='+qty);	
}
function setPromotionCodeAndAddProduct(product_id,promotionCode,qty)
{

	new Request({
		method: 'post',
		url: href+"p_include/checkout_ajax_func.html",
		onComplete : function()
		{
			$('mini_cart_promoCode').value=promotionCode;
			addProduct(product_id,0,qty);
		}
	}).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,checkPoints)
{
	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);
				if(values['expedited'] == 1)
				{
					var expedited_message = '<br /><span class="justRed">Orders placed after 3 p.m. ship the next business day. This excludes weekends and U.S. holidays.</span>';
				}
				else
				{
					var expedited_message = '';
				}
				$('shopping_cart_shippingDropDown').innerHTML = values['shippingDrowDown']+expedited_message;
				

				try
				{
					//billMeLater_promotion_checkbox
					if(($('shopping_cart_credit_card_total').innerHTML * 1) >= 250)
					{
						$('billMeLater_promotion_checkbox').disabled = false;
					}
					else
					{
						$('billMeLater_promotion_checkbox').disabled = true;
						$('billMeLater_promotion_checkbox').checked = false;
					}
				}
				catch(err)
				{

				}

				
				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 greater than 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/positivePromoCodeIndicatorGray.jpg';
				}
				else
				{
					$('shopping_cart_promo_image').src=href+'p_images/pendingPromoCodeIndicator.gif';
				}

				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';
			var extraNote = '';
			if(values['country'].toUpperCase()=='UNITED STATES' && $('overnightShippingSpecial').get('html')=='true')
			{
				extraNote = ' Or, for only <span class="remainingFreeShippingBalance">$4.95</span> more, ship this order overnight!';
			}
			if(freeShippingAmount>49)
			{
				$('miniCartShippingHeader').innerHTML='CONGRATULATIONS!';
				$('miniCartShippingText').innerHTML='Your order qualifies for <strong>'+shippingNotificationLabel+' SHIPPING!'+extraNote+'</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.'+extraNote;
			}
			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.gif';
			}
			//alert(values['displayEmptyMessage']);
			if(values['productQty']==0 && values['displayEmptyMessage']=='1')
			{
				$('emptyCartMessage').innerHTML = ' You currently have no items in your cart. ';
			}
			else
			{
				$('emptyCartMessage').innerHTML = '';
			}
			for (var i in values['couponExemptionMessages'])
			{
				if($(i))
					$(i).innerHTML=values['couponExemptionMessages'][i];
			}
			
			if(checkPoints && $('points_amount_used')) validatePointsPaymentAmount();
		}
	}).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);
}
function acceptSubscriptionTOS(ele)
{
	var accepted = ele.checked;
	new Request({
		url : 'p_include/ajax_func.html',
		method : 'post',
		onComplete:function(response){
			
		}
	}).send('func=acceptSubscriptionTOS&accepted='+accepted);
}
function sendToFriendPopUp(type,product_id,template_id)
{
	new Request({
		method:'post',
		url:'p_include/ajax_func.html',
		evalScripts:true,
		onComplete:function(response)
		{
			showPopUp(response);
		}
	}).send('func=tellAFriendPopUp&type='+type+'&product_id='+product_id+'&template_id='+template_id);

}
function forcePositiveInt(input)
{
	input.value=Math.floor(input.value*1);
	if(isNaN(input.value) || (1*input.value) < 1)
	{
		input.value = 1;		
	}
}
window.addEvent('domready',function(){
//	alert('got here at least');
	if($('reviewBreakDown'))
	$('reviewBreakDown').set('tween',{
		onComplete:function(){
			$('reviewBreakDown').style.display='block';
		},
		duration:1
	}).tween('opacity',0);
});
function displayReviewBreakDown(starsDiv)
{
	var left = $('starsDiv').getLeft();
	var top = $('starsDiv').getTop();
	if(Browser.Engine.name != 'trident')
	{
		$('reviewBreakDown').style.top=top;
		$('reviewBreakDown').style.left=(left);
	}
	else
	{
		$('reviewBreakDown').setStyles({'top':top,'left':(left-65)});
	}
	$('reviewBreakDown').style.backgroundColor='#FFFFFF';
	$('reviewBreakDown').set('tween',{
		duration:500
	}).tween('opacity',1);
}
function hideReviewBreakDown()
{
	$('reviewBreakDown').set('tween',{
		duration:500
	}).tween('opacity',0);
}
