function selectNewRegisteredUser() {
	if ($('#customerTypeReturning').attr("checked")) {
		$('#repeatLoginDiv').show();
		$('#newUserDiv').hide();
	} else {
		$('#repeatLoginDiv').hide();
		$('#newUserDiv').show();
	}
        
}

function changeQuantity(f, i) {
	var v = parseInt($('#'+f).val()) + i;
	if (f.disabled) return false;
	if (v < 1) {
		if (!confirm("Are you sure? This will remove the item from your order.")) return false;
	}
	$('#'+f).val(v).trigger('change');
}

function updatePriceQty(keyup) {

	var basePrice = $('#basePrice').val();
	var cSymbol = $('#currencySymbol').val();
	var sQty = $('#selectQuantity').val();

	if (keyup!=1 && (!sQty || isNaN(sQty))) {
		sQty = 1;
		$('#selectQuantity').val(1);
	} else if (keyup!=1 && (!isNaN(sQty) && sQty > 20)) {
		alert("To order more than 20 items, please contact us.");
		sQty = 19;
		$('#selectQuantity').val(19);
	}

	var totalPrice = sQty * basePrice;
	totalPrice = totalPrice.toFixed(2);
	totalPrice = totalPrice.toString(10);
	
	$('#priceDisplay').html(cSymbol + totalPrice);

	//if ($('#productVariantID').val() == "2") {
	//	$('#buyButton').hide();
	//	$('#outOfStock').show();
	//} else {
	//	$('#buyButton').show();
	//	$('#outOfStock').hide();
	//}
}

function addToCart() {
	var id = $('#productVariantID').val();
	var q = $('#selectQuantity').val();

	if (!q || isNaN(q)) {
		alert("Please enter a quantity before adding to your cart.");
		return false;
	} else if (!id) {
		alert("There seems to be an error on the page. Please try refreshing your browser.");
		return false;
	}

	addToCartAJAX(id, q);
}

function addToCartAJAX(id, q) {
	$.ajax({
		url: '/ajax/public/addToCart?id='+id+'&q='+q,
		dataType: 'script',
		success: function() {
			alert("Your cart has been updated. Please see the 'Shopping Basket' box for details.");
		},
		error: function(data) {
			alert("Sorry, an error occurred. Please try refreshing the page.");			
		}
	});
}

function refreshCartAJAX(currencyCode) {
	var action = '/ajax/public/refreshCart';
	if (currencyCode) {
		action += '?currencyCode=' + currencyCode;
	}
	$.getScript(action);
}

function getVariantDataAJAX(id) {
	$.getJSON('/ajax/public/getVariantData?id='+id, function (data) {
		if (data.success == 1) {
			$('#productImage').attr('src', '/pictures/products/'+data.variant.image);
			$('#basePrice').val(data.variant.price);
			$('#currencySymbol').val(data.variant.currencyCode);
			updatePriceQty();
		} else {
			if (data.error) {
				alert(data.error);
			} else {
				alert("Sorry, an error occurred. Please try refreshing the page.");
			}
		}
	});
}

function updateCurrencyAJAX(cur, id) {
	$.getJSON('/ajax/public/refreshPricing&id='+id+'&currency='+cur, function (data) {
		if (data.success == 1) {
			r = data.response;
			var sel = $('#productVariantID').val();
			$('#currencySymbol').val(r.currencySymbol);
			$.each(r.pricing, function (i, p) {
				if ($('#variantPricingLabel_' + p.variant_id).length) {
					if (p.variant_id == sel) {
						$('#basePrice').val(p.price);
						updatePriceQty();
					}
					$('#variantPricingLabel_' + p.variant_id).html(p.size);
					$('#variantPricingValue_' + p.variant_id).html(r.currencySymbol + p.price);
				}
			});
			if ($('#freePPNotice').length > 0) {
				switch (cur) {
					case 'GBP':
						$('#freePPNotice').html(r.currencySymbol + '30');
						break;
					case 'EUR':
						$('#freePPNotice').html(r.currencySymbol + '50');
						break;
					case 'USD':
						$('#freePPNotice').html(r.currencySymbol + '50');
						break;
				}
			}
		} else {
			if (data.error) {
				alert(data.error);
			} else {
				alert("Sorry, an error occurred. Please try refreshing the page.");
			}
		}
	});
}

function getPricingSetAJAX(type, currency) {
	if (!type) type = 'all';
	var url = '/ajax/public/getPricingSet&type='+type;
	if (currency) url += '&currency=' + currency;
	$.getJSON(url, function (r) {
		if (r.success == 1) {
			$('#cartSummaryItems').html(r.cartItems);
			$('#cartSummaryValue').html(r.cartValue);
			$.each(r.pricing, function (i, p) {
				if ($('#variantPriceSpan_'+p.id).length) {
					$('#variantPriceSpan_'+p.id).html(p.currency + p.price);
				}
				if ($('#variantMBSaving_'+p.id).length && p.multibuy_saving > 0) {
					if (p.freePP == 1) {
						$('#variantMBSaving_'+p.id).html(p.currency + p.multibuy_saving + ' and Free P&amp;P');
					} else {
						$('#variantMBSaving_'+p.id).html(p.currency + p.multibuy_saving);
					}
				}
				if ($('.allProductPriceSpan_'+p.id).length) {
					$('.allProductPriceSpan_'+p.id).html(p.currency + p.price);
					if (p.multibuy_saving > 0) {
						if (p.freePP == '1') {
							$('.allProductMBSavingSpan_'+p.id).html(p.currency + p.multibuy_saving + ' and Free P&amp;P');
						} else {
							$('.allProductMBSavingSpan_'+p.id).html(p.currency + p.multibuy_saving);
						}
					}
				}
				if ($('.productPriceSpan_'+p.id).length) {
					$('.productPriceSpan_'+p.id).html(p.currency + p.price);
				}
                                
                              
			});
		} else {
			if (r.error) {
				alert(r.error);
			} else {
				alert("Sorry, an error occurred. Please try refreshing the page.");
			}
		}
	});
}

function getMultibuyPricing(type, currency) {
	var url = '/ajax/public/getMultibuyPricing?type=' + type;
	if (currency) url += '&currency=' + currency;
	$.getScript(url);
}

function getUserPassword() {
	$('#loadingSpinner').show();
	$('#loginStatusDisplay').load('/ajax/public/resetPassword', {
		email: $('#loginEmail').val()
	}, function() {
		$('#loadingSpinner').hide();
	});
}

function doCustomerLogin(target) {
	if (!target) {
		var target = 'checkout';
	}
	$('#loadingSpinner').show();
	
	$('#loginStatusDisplay').load('/ajax/public/customerLogin', {
			target: target,
			email: $('#loginEmail').val(),
			password: $('#loginPassword').val()
		}, function() {
			$('#loadingSpinner').hide();                       
		}
	);
}

function loginReturnCustomer() {
	$('#returnLoginStatus').load('/ajax/public/customerLogin', {
		target: 'return',
		email: $('#bill_email').val(),
		password: $('#returnPassword').val()
	}, function() {
		$('#returnPassword').val('');
		$('#returnPassword').focus();
	});
}

function numeralsOnly(evt) {
	evt = (evt) ? evt : event;
	var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
	if (charCode > 31 && (charCode < 48 || charCode > 57)) {
		return false;
	}
	return true;
}

function validateMailingListForm(f) {
	if (f.firstName.value == '' || f.lastName.value == '' || f.email.value == '') {
		alert("Please complete all three fields to continue.");
		return false;
	} else {
		f.submit();
		return true;
	}
}

function validateYesPlease(f) {
	var requiredFields = new Array("firstName", "lastName", "emailAddress",
		"topPublications", "radioStations", "topWebsites", "preferredShop",
		"address1", "stateCounty", "zipCode", "country");
	
	var errorState = 0;
	
	for (var i = 0; i < requiredFields.length; i++) {
		with (f.elements[requiredFields[i]]) {
			switch (tagName) {
				case 'INPUT':
					if (value == '') {
						errorState = 1;
					}
					break;
				case 'SELECT':
					if (selectedIndex == 0) {
						errorState = 1;
					}
					break;
			}
		}
	}
	
	var gotActive = 0;
	
	for (var i = 0; i < f.age.length; i++) {
		if (f.age[i].checked) gotActive = 1;
	}
	
	if (gotActive == 0) {
		errorState = 1;
	}
	
	gotActive = 0;
	
	for (var i = 0; i < f.gender.length; i++) {
		if (f.gender[i].checked) gotActive = 1;
	}
	
	if (gotActive == 0) {
		errorState = 1;
	}	
	

	if (errorState == 1) {
		alert("Please complete all asterisked fields.");
		return false;
	}

	f.Submit1.disabled = true;
	f.submit();
	return true;	
}

function validateBCNRequest(f) {
	var requiredFields = new Array("firstName", "lastName", "emailAddress",
		"address1", "stateCounty", "zipCode");
	
	var errorState = 0;
	
	for (var i = 0; i < requiredFields.length; i++) {
		with (f.elements[requiredFields[i]]) {
			switch (tagName) {
				case 'INPUT':
					if (value == '') {
						errorState = 1;
					}
					break;
				case 'SELECT':
					if (selectedIndex == 0) {
						errorState = 1;
					}
					break;
			}
		}
	}

	if (errorState == 1) {
		alert("Please complete all asterisked fields.");
		return false;
	}

	f.Submit1.disabled = true;
	f.submit();
	return true;	
}

function validateSampleRequest(f) {
	var requiredFields = new Array("firstName", "lastName", "emailAddress",
		"topPublications", "radioStations", "topWebsites", "preferredShop",
		"howHeard", "address1", "stateCounty", "zipCode", "whyTrial");
	
	var errorState = 0;
	
	for (var i = 0; i < requiredFields.length; i++) {
		with (f.elements[requiredFields[i]]) {
			switch (tagName) {
				case 'INPUT':
					if (value == '') {
						errorState = 1;
					}
					break;
				case 'SELECT':
					if (selectedIndex == 0) {
						errorState = 1;
					}
					break;
				case 'TEXTAREA':
					if (value == '') {
						errorState = 1;
					}
			}
		}
	}
	
	var gotActive = 0;
	
	for (var i = 0; i < f.age.length; i++) {
		if (f.age[i].checked) gotActive = 1;
	}
	
	if (gotActive == 0) {
		errorState = 1;
	}
	
	gotActive = 0;
	
	for (var i = 0; i < f.gender.length; i++) {
		if (f.gender[i].checked) gotActive = 1;
	}
	
	if (gotActive == 0) {
		errorState = 1;
	}
	
	gotActive = 0;
	
	for (var i = 0; i < f.everDisappointed.length; i++) {
		if (f.everDisappointed[i].checked) gotActive = 1;
	}
	
	if (gotActive == 0) {
		errorState = 1;
	}
	
	if (errorState == 1) {
		alert("Please complete all asterisked fields.");
		return false;
	}

	f.Submit1.disabled = true;
	f.submit();
	return true;
}

function showCurrencyHelp() {
	var chelpWin = window.open('/which_currency_popup.htm', chelpWin, 'resizable=yes,status=no,scrollbars=no,toolbar=no,height=385,width=500');
	chelpWin.focus();
}

function displayUpsellDiv() {
	var div = document.getElementById('upsellAlertDiv');
	var anchor = document.getElementById('checkoutOrderTotal');
	if (!div || !anchor) return false;
	div.style.display = 'block';
	var pos = findPos(anchor);
	div.style.left = pos[0] + anchor.offsetWidth - 5 + 'px';
	div.style.top = pos[1] - div.offsetHeight + (anchor.offsetHeight) + 'px';
}

function hideUpsellDiv() {
	var div = document.getElementById('upsellAlertDiv');
	if (!div) return false;
	div.style.display = 'none';
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}

function searchReferrerLog() {
	if (!document.createElement) return;
	ref = document.referrer;
	
	if (ref.indexOf('?') == -1) return;
	qs = ref.substr(ref.indexOf('?')+1);
	qsa = qs.split('&');
	var url = '';
	for (i=0;i<qsa.length;i++) {
		qsip = qsa[i].split('=');
	        if (qsip.length == 1) continue;
        	if (qsip[0] == 'q' || qsip[0] == 'p') { // q= for Google, p= for Yahoo
				url = 'srchTerm=' + qsip[1];				
	        }
	}
	if (url != '') {
		var tempRO;
		tempRO = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
		var tempDO = new Date();
		var requestURL = '/ajax/rpc.php?timestamp=' + tempDO.getTime() + '&action=registerReferrer&' + url;
		tempRO.open('get', requestURL);
		tempRO.send(null);
	}
	
}

function autoHoverInit() {
	$('img.auto-hover').live('mouseover', function() {
		$(this).attr('src', $(this).attr('src').replace(/_up/, "_over"));
	});
	$('img.auto-hover').live('mouseout', function() {
		$(this).attr('src', $(this).attr('src').replace(/_over/, "_up"));
	});
}

searchReferrerLog();


