;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

if(!this.JSON){JSON=function(){function f(n){return n<10?'0'+n:n;}
Date.prototype.toJSON=function(){return this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z';};var m={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};function stringify(value,whitelist){var a,i,k,l,r=/["\\\x00-\x1f\x7f-\x9f]/g,v;switch(typeof value){case'string':return r.test(value)?'"'+value.replace(r,function(a){var c=m[a];if(c){return c;}
c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+
(c%16).toString(16);})+'"':'"'+value+'"';case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
if(typeof value.toJSON==='function'){return stringify(value.toJSON());}
a=[];if(typeof value.length==='number'&&!(value.propertyIsEnumerable('length'))){l=value.length;for(i=0;i<l;i+=1){a.push(stringify(value[i],whitelist)||'null');}
return'['+a.join(',')+']';}
if(whitelist){l=whitelist.length;for(i=0;i<l;i+=1){k=whitelist[i];if(typeof k==='string'){v=stringify(value[k],whitelist);if(v){a.push(stringify(k)+':'+v);}}}}else{for(k in value){if(typeof k==='string'){v=stringify(value[k],whitelist);if(v){a.push(stringify(k)+':'+v);}}}}
return'{'+a.join(',')+'}';}}
return{stringify:stringify,parse:function(text,filter){var j;function walk(k,v){var i,n;if(v&&typeof v==='object'){for(i in v){if(Object.prototype.hasOwnProperty.apply(v,[i])){n=walk(i,v[i]);if(n!==undefined){v[i]=n;}}}}
return filter(k,v);}
if(/^[\],:{}\s]*$/.test(text.replace(/\\./g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof filter==='function'?walk('',j):j;}
throw new SyntaxError('parseJSON');}};}();}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function qtyRemove() {
	var currentQty = parseInt($('.quantityBox').text());
	if (currentQty > 0) {
		currentQty--;
	}
	$('.quantityBox').text(currentQty);
}
function  qtyAdd() {
	var currentQty = parseInt($('.quantityBox').text());	
	
		currentQty++;
	
	$('.quantityBox').text(currentQty);
}

function handleBasket(data, textStatus, XMLHttpRequest, stayClosed) {
	$('.miniMinus,.miniPlus').unbind('click');
	var basketItem = '';
	var row = '';
	var price = 0;
	var totalItems = 0;
	var totalPrice = 0;
	var multiPurchaseDiscount = 0;
	var quantCounter = 0;
	var lastMultiPurchaseDiscountAppliedAt = 0;
	var rowTriggeredMultiPurchaseDiscount = 1;
	var authors = '';
	var itemWord = 'item';
	var itemType = 'Printed Book';
	var series_join = '';
	
	if (!stayClosed) {
		var stayClosed = 0;
		//basket = ObjectHandler.getCloneOfObject(data);
		basket = data;
	}
	if (data.length) {
		$('#basketStatus').text('You have added items to your cart');		
	} else {
		$('#basketStatus').text('You don\'t have anything in your cart!');			
		$('#popBasketSummary').text('You have no items in your cart');
	}
	$('#popBasketContents').empty();
	for (var i=0;i<data.length;i++) {
		basketItem = data[i];
		price = (basketItem.PRODUCT_PRICE)*basketItem.QUANTITY;
		totalPrice += price;
		totalItems += basketItem.QUANTITY;
		quantCounter += basketItem.QUANTITY;
		if (Math.floor(quantCounter/4) >= 1 && lastMultiPurchaseDiscountAppliedAt != Math.floor(quantCounter/4)) {
			rowTriggeredMultiPurchaseDiscount = 1;
			multiPurchaseDiscount += (basketItem.PRODUCT_PRICE*(Math.floor(quantCounter/4)-lastMultiPurchaseDiscountAppliedAt));
			price -= (basketItem.PRODUCT_PRICE*(Math.floor(quantCounter/4)-lastMultiPurchaseDiscountAppliedAt));
			lastMultiPurchaseDiscountAppliedAt = Math.floor(quantCounter/4);			
		}
		authors = '';
		if (basketItem.AUTHORS.length) {
			authors += '<br />By ' + basketItem.AUTHORS.join(', ');
		}
		if (basketItem.TYPE == 'digital') {
			itemType = 'PDF download';
		} else if (basketItem.TYPE == 'epub') {
			itemType = 'Ebook download';
		} else if (basketItem.TYPE == 'kindle') {
			itemType = 'Kindle download';
		} else {
			itemType = 'Printed book';	
		}
		if (basketItem.SERIES_ID != 3) {
			series_join = ': ';
		} else {
			series_join = ' ';	
		}
		row = '<div class="divide361">&nbsp;</div><div class="floatLeft57 padE12"><img src="images/_titles/miniBasket/'+basketItem.PRODUCT_IMAGE+'" alt="'+basketItem.PRODUCT_TITLE+'" width="57"  /></div><div class="floatLeft222"><p><strong class="textBlue">'+basketItem.SERIES_NAME+series_join+basketItem.PRODUCT_TITLE+'</strong> ('+itemType+')'+authors+'</p><div class="floatLeft80">Quantity: '+basketItem.QUANTITY+'</div><div class="quantityIncrements"><a href="javascript:void(0);" class="miniMinus"><img src="images/off_minus.gif" alt="less" name="minus" width="16" height="14" border="0" class="miniMinus" id="miniMinus_'+i+'" /></a></div><div class="quantityIncrements"><a href="javascript:void(0);" class="miniPlus"><img src="images/off_plus.gif" alt="add one" name="plus" width="16" height="14" border="0" class="miniPlus" id="miniPlus_'+i+'" /></a></div><br clear="all" /></div><div class="floatLeft70r padN50">'+currencySymbol+' '+price.toFixed(2)+'</div><br clear="all" />';
		/*row = '<div class="floatLeft40"><img src="images/products/thumbnails/'+basketItem.PRODUCT_THUMBNAILIMAGE+'" alt="'+basketItem.PRODUCT_TITLE+'" width="40" height="36" /></div><div class="floatLeft247">'+basketItem.PRODUCT_TITLE+variant_title+'<br /><span class="textGrey"><div class="floatLeft179"><div class="floatLeft75">quantity: '+basketItem.QUANTITY+'</div><div class="floatLeft16"><a href="javascript:void(0)" class="miniMinus" id="miniMinus_'+i+'"><img src="images/off_miniMinus.png" alt="less" name="miniMinus" width="16" height="14" border="0" /></a></div><div class="floatLeft16"><a href="javascript:void(0)" class="miniPlus" id="miniPlus_'+i+'"><img src="images/off_miniPlus.png" alt="more" name="miniPlus" width="16" height="14" border="0" /></a></div><br clear="all" /></div><div class="floatLeft68r">&pound;'+price.toFixed(2)+'</div></span><br clear="all" /></div><br clear="all" /><div class="divide292"><img src="images/spacer.gif" alt="" /></div>';*/
		$('#popBasketContents').append(row);
	}
	totalPrice -= multiPurchaseDiscount;
	$('#ajaxBasketNumItems').text(totalItems);
	if (totalItems != 1) {
		itemWord += 's';
	}
	if (totalItems) {
		$('#popBasketSummary').text('You have '+totalItems+' '+itemWord+' in your cart');
	} else {
		$('#popBasketSummary').text('You have no items in your cart');
	}	
	$('#ajaxBasketTotalPrice,#popBasketTotalPrice').html(currencySymbol+totalPrice.toFixed(2));
	if (!stayClosed) {
		$('.popBasket').fadeIn('fast');
	}
	$('.miniMinus,.miniPlus,.largeMinus,.largePlus').bind('click',function(event) {
			handleQuantityChange(event);												
	});
}

function handleTypeChange() {
	var type = $('input[name="productType"]:checked').val();
	newPrice = prices[type];
	$('#titlePrice').html(currencySymbol+newPrice.toFixed(2));
	if (!product_inStock) {
		$('#deliveryInfo').text('\(currently out of stock\)');
	} else if (type == 'hardcopy') {
		if (region != 'GBP') {
			$('#deliveryInfo').html('(Our delivery cost is a flat fee of '+currencySymbol+deliveryPrices.first_item.toFixed(2)+' so the more you order the better!)');
		} else {
			$('#deliveryInfo').html('\(Free UK Delivery!\)');
		}
	} else {
		$('#deliveryInfo').html('');	
	}
}

function addToBasket() {
	var currentQty = parseInt($('.quantityBox').text());
	var type='digital';
	if ($('input[name="productType"]').length < 2) {
		var type = $('input[name="productType"]').val();	
	}
	if ($('input[name="productType"]:checked').length && $('input[name="productType"]:checked').val()=='hardcopy') {
		type = 'hardcopy';
	} else if ($('input[name="productType"]:checked').length && $('input[name="productType"]:checked').val()=='epub') {
		type = 'epub';	
	} else if ($('input[name="productType"]:checked').length && $('input[name="productType"]:checked').val()=='kindle') {
		type = 'kindle';	
	}
	
	if (currentQty) {
		$.getJSON('/_ajax/basket_add.cfm',{rand:Math.random(),product:currentProduct,quantity:currentQty,type:type},handleBasket);
		$.scrollTo(0,1000);
	}
}

function closeBasket() {
	$('.popBasket').fadeOut('fast');	
}

function openBasket() {
	$('.popBasket').fadeIn('fast');	
}

function handleQuantityChange(event) {
	var id = event.currentTarget.id.split('_');
	var basketItem2 = '';	
	id[1] = parseInt(id[1]);
	/*if (console) {
		console.log(event);
	}*/
	basketItem2 = basket[id[1]];
	if (id[0] == 'miniMinus' || id[0] == 'largeMinus') {
		basketItem2.QUANTITY--;
		if (basketItem2.QUANTITY < 1) {
			basket.splice(id[1],1);
		}
		
	} else {
		basketItem2.QUANTITY++;
						
	}
	//$('.miniMinus,.miniPlus').die('click');
	
	if (id[0] == 'largeMinus' || id[0] == 'largePlus') {
		$('.largeMinus,.largePlus').unbind('click');
		updateBasket(1);
		handleBasket(basket, null, null, 1);
	} else {
		updateBasket();
		handleBasket(basket);
	}	
}

function updateBasket(refreshVar) {
	$.post('/_ajax/basket_save.cfm',{rand:Math.random(),basket:JSON.stringify(basket)},function(data) {
		//
		if (refreshVar) {
			location.reload(true);
		}
	});	
}



function isValidEmail(email) {
		var emailRegExp = /^\w(?:\w|-|\.(?!\.|@))*@\w(?:\w|-|\.(?!\.))*\.\w{2,4}/ 
		var result = email.match(emailRegExp);
		if ((result && result[0].length != email.length) || !result) {
			return false
		} else {
			return true
		}
	}
	
	function handleSubscription() {
		
		var email = $('#newsletterEmailAddress').val();
		if (!email.length || !isValidEmail(email)) {
			alert('Please enter a valid email address');
		} else {
			$.get('/_ajax/newsletter_subscribe.cfm',{rand:Math.random(),email:email},function(data) {
				var response = parseInt(data);
				if (response == 0) {
					alert('Please enter a valid email address');
				} else if (response == -1) {
					alert('You are already subscribed to this newsletter!');	
				} else {
					alert('Thank you for subscribing!');	
				}
			});	
		}
	}
	
function chkDiscount() {
	if (!$('#discountCode').val().length) {
		alert('Please enter a discount code in the box.');
	} else {
		$.getJSON('/_ajax/apply_discount_code.cfm',{rand:Math.random(),code:$('#discountCode').val()},function(data) {
			if (data.VALID == 1) {
				if (data.INDATE == 1) {
					alert('The \''+data.TITLE+'\' discount has been applied!\n\nClick \'OK\' to continue.');
					location.reload(true);
				} else {
					alert('Sorry, but this discount code has expired.');	
				}
			} else {
				alert('Sorry, but this discount code was not recognised. Please try again.');	
			}
		});	
	}
}

function removeDiscount(event) {
	var id = event.currentTarget.id.split('_');
	$.get('/_ajax/remove_discount_code.cfm',{rand:Math.random(),index:id[1]},function(data) {
		location.reload(true);																			  
	});
}

function chkLogin() {
	var errArr = new Array();
	if (!$('#emailAddress').val().length || !isValidEmail($('#emailAddress').val())) {
		errArr[errArr.length] = 'Please enter a valid email address';
	}
	if ($('#loginRegisteredNo:checked').length) {
		// needs to register
		if (errArr.length) {
			alert('Please complete the following:\n\n- '+errArr.join('\n- '));
		} else {
			window.location.href='login.cfm?register=1&email='+$('#emailAddress').val();
		}
	} else {
		//login
		if (!$('#password').val().length) {
			errArr[errArr.length] = "Your password";
		}
		if (errArr.length) {
			alert('Please complete the following:\n\n- '+errArr.join('\n- '));
		} else {
			$.get('/_ajax/login.cfm',{rand:Math.random(),email:$('#emailAddress').val(),password:$('#password').val()},function(data) {
				if (data=='0') {
					alert('We\'re sorry, but your account could not be found from the login details you supplied.\n\nPlease check your email address and password and try again.');	
				} else {
					window.location.href='login.cfm?login='+data;
				}
			});
		}
	}
}

function chkRegistration(yourAccount) {
	var errArr = new Array();
	var scriptAction = 'register';
	if (typeof(yourAccount) != 'undefined') {
		scriptAction = yourAccount; 
	}
	if (!$('#title option:selected').length) {
		errArr[errArr.length] = 'Title';
	}
	if (!$('#firstname').val().length) {
		errArr[errArr.length] = 'First name';
	}
	if (!$('#lastname').val().length) {
		errArr[errArr.length] = 'Second name';
	}
	var emailOK = 1;
	if (!$('#emailAddress').val().length || !isValidEmail($('#emailAddress').val())) {
		errArr[errArr.length] = 'Please enter a valid email address';
		emailOK = 0;
	} else if ($('#emailAddress').val() != $('#emailAddress2').val())  {
		errArr[errArr.length] = 'Email addresses do not match, please retype your email address';
		emailOK = 0;
	}
	if (!$('#telephone').val().length) {
		errArr[errArr.length] = 'Telephone';
	}
	if (!$('#password').val().length >= 6) {
		errArr[errArr.length] = 'Password must be 6 characters or more';
	} else if ($('#password').val() != $('#password2').val())  {
		errArr[errArr.length] = 'Passwords do not match, please retype your new password';
	}
	if (!$('#jobTitle option:selected').val().length) {
		errArr[errArr.length] = 'Profession';
	}
	if (!$('#country option:selected').val().length) {
		errArr[errArr.length] = 'Country of residence';
	}
	if (!emailOK) {
		alert('Please complete the following:\n\n- '+errArr.join('\n- '));
	} else {
		$.get('/_ajax/check_email.cfm',{rand:Math.random(),email:$('#emailAddress').val()}, function(data) {
			var result = parseInt(data);
			if (result) {
				errArr[errArr.length] = 'The email address your supplied is already in use for an existing account.';	
			}
			if (errArr.length) {
				alert('Please complete the following:\n\n- '+errArr.join('\n- '));
			} else {
				var arrCategories = new Array();
				$('input:checkbox[name=categories]:checked').each(function() {
					arrCategories.push($(this).val());													   
				});
				
				
				$.get('/_ajax/'+scriptAction+'.cfm',{
						rand:Math.random(),
						title:$('#title').val(),
						firstname:$('#firstname').val(),
						lastname:$('#lastname').val(),
						email:$('#emailAddress').val(),
						password:$('#password').val(),
						country:$('#country').val(),
						telephone:$('#telephone').val(),
						categories:arrCategories.join(),
						newsletterSubscribe:$('input:checkbox[name=newsletterSubscribe]:checked').length,						
						organisation:$('#organisation').val(),
						jobTitle:$('#jobTitle option:selected').val(),
						referral:$('#referral option:selected').val(),
						thirdPartyOptIn:$('input:checkbox[name=thirdPartyOptIn]:checked').length
					}, function(data) {
						if (typeof(yourAccount) != 'undefined') {
							alert('Thank you, your details have been saved.'); 
						} else {
							window.location.href='/login.cfm?login='+data;
						}
						
					}
				);	
			}
		});	
	}	
}

function chkAddressForm() {
	var errArr = new Array();
	if (!$('#firstname').val().length) {
		errArr[errArr.length] = 'First name';
	}
	if (!$('#lastname').val().length) {
		errArr[errArr.length] = 'Second name';
	}
	if (!$('#address1').val().length) {
		errArr[errArr.length] = 'Address';
	}
	if (!$('#town').val().length) {
		errArr[errArr.length] = 'Town/City';
	}
	if ($('#country').val() == '230' && !$('#state').val().length) {
		errArr[errArr.length] = 'State';
	}
	if (!$('#postcode').val().length) {
		errArr[errArr.length] = 'Postcode/Zip';
	}
	if (errArr.length) {
		alert('Please complete the following\n\n- '+errArr.join('\n- '));
	} else {
		$.post('/_ajax/address_save.cfm',{
			   rand:Math.random(),
			   address:$('#address').val(),
			   firstname:$('#firstname').val(),
			   lastname:$('#lastname').val(),
			   address1:$('#address1').val(),
			   address2:$('#address2').val(),
			   address3:$('#address3').val(),
			   town:$('#town').val(),
			   county:$('#county').val(),
			   postcode:$('#postcode').val(),
			   country:$('#country').val(),
			   state:$('#state').val(),
			   telephone:$('#telephone').val()
		}, function(data) {
			window.location.href='/order-addresses.cfm';	
		});	
	}
}

function chkCountryState() {
	if ($('#country').val()=='230' && !$('#stateDiv:visible').length) {
		$('#stateDiv').slideDown('fast');
	} else if ($('#stateDiv:visible').length && $('#country').val() != '230') {
		$('#stateDiv').slideUp('fast');
	}
}

function addressEdit(event) {
	var id = $('img',event.currentTarget).attr('id').split('_')[1];
	window.location.href='/order-addresses-edit.cfm?address='+id;
}

function addressDelete(event) {
	var id = $('img',event.currentTarget).attr('id').split('_')[1];
	if (confirm('Are you sure you want to delete this address from your address book?')) {
		$.get('/_ajax/address_delete.cfm',{rand:Math.random(),address:id},function(data) {
			location.reload(true);																		   
		});
	}
}

function chkAddress() {
	var addressOk = 1;
	var errArr = new Array();
	var addressTypes = 1;
	var billing = 0;
	var delivery = 0;
	if (!$('input[name=billingAddress]:checked').length) {
		addressOk = 0;
		errArr[errArr.length] = "Billing Address";
	} else {
		billing = $('input[name=billingAddress]:checked').val();	
	}
	if ($('input[name=deliveryAddress]').length) {
		addressTypes++;	
	}
	if (addressTypes == 2 && !$('input[name=deliveryAddress]:checked').length) {
		addressOk = 0;
		errArr[errArr.length] = "Delivery Address";
	} else if (addressTypes ==2) {
		delivery = $('input[name=deliveryAddress]:checked').val();	
	}
	if (addressOk) {
		$.get('/_ajax/addresses_set.cfm',{rand:Math.random(),billingAddress:billing,deliveryAddress:delivery,addressTypes:addressTypes},function(data) {
			window.location.href='order-confirm.cfm';																										   
		});
	} else {
		if (errArr.length > 1) {
			alert('Please select a delivery address AND a billing address to continue with your order.');
		} else if (addressTypes == 2) {
			if (!billing) {
				alert('Please select a billing address to continue with your order.');
			} else {
				alert('Please select a delivery address to continue with your order.');
			}
		} else {
			alert('Please select a billing address to continue with your order.');	
		}
		
	}	
}

function highlightAddress(event) {
	var target = event.currentTarget.id.split('_');
	var type = target[0];
	var id = target[1];
	if (type == 'billingAddress') {
		$('input[name=billingAddress]').parent().parent().removeClass('highlighted');
		$('input[name=billingAddress]:checked').parent().parent().addClass('highlighted');
	} else {
		$('input[name=deliveryAddress]').parent().parent().removeClass('highlighted');
		$('input[name=deliveryAddress]:checked').parent().parent().addClass('highlighted');	
	}
}

function chkForgotPassword() {
	if (!$('#emailAddress').val().length || !isValidEmail($('#emailAddress').val())) {
		alert('Please enter the email address you previously registered with.');
	} else {
		$.get('/_ajax/password_reminder.cfm',{rand:Math.random(),email:$('#emailAddress').val()},function(data) {
			if (data == '1') {
				alert('Thank you! We have sent a reminder of your password to your email address.');	
			} else if (data == '0') {
				alert('We could not find that email address in our records. It does not appear to have been registered with us!');
			}
		});	
	}
}

function selCategories() {
	if ($('input[name="categoriesAll"]:checked').length) {
		$('input[name="categories"]').attr('checked','checked');
	} else {
		$('input[name="categories"]').removeAttr('checked');
	}
}

function chkCategoriesToggle() {
	var numCategories = $('input[name="categories"]').length;
	if ($('input[name="categoriesAll"]:checked').length && $('input[name="categories"]:checked').length != numCategories) {
		$('input[name="categoriesAll"]').removeAttr('checked');	
	}
}

function chkReview() {
	var errArr = new Array();
	var score = parseInt($('#score').val());
	if (isNaN(score) || !score) {
		errArr[errArr.length] = 'Please rate this title by clicking on the stars.';	
	}
	if (errArr.length) {
		alert(errArr[0]);
	} else {
		$.post('/_ajax/review_save.cfm',{rand:Math.random(),score:$('#score').val(),review:$('#review').val(),product:$('#product').val(),comment:$('#review_comments').val()},function(data) {
				window.location.href='/your-reviews.cfm';
		});	
	}
	
}

function setupScoring() {
	var star = {'off':new Image(),'on':new Image()};
	star.off.src = '/images/off_star.jpg';
	star.on.src = '/images/on_star.jpg';
	var score = parseInt($('#score').val());
	var i=0;
	if (score) {
		for (i=1;i <= score;i++) {
			$('#score_'+i).attr({'src':star.on.src});
		}
	}
	$('.scoreLink').bind('click',function(event) {
		var newScore = parseInt($('img',event.currentTarget).attr('id').split('_')[1]);	
		var s = 0;
		$('#score').val(newScore);
		$('.scoreLink img').attr({'src':star.off.src});
		if (newScore) {
		for (s=1;s <= newScore;s++) {
				$('#score_'+s).attr({'src':star.on.src});
			}
		}
	
	});
	$('#commentSaveLink').bind('click',chkReview);
				
}

function toggleTitleDescription() {
	if ($('#productDescription:visible').length) {
		$('#productDescription').slideUp('slow');
		$('#toggleDescriptionLink').text('[+] Show Title description');
	} else {
		$('#productDescription').slideDown('slow');
		$('#toggleDescriptionLink').text('[-] Hide Title description');	
	}
}

var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-2416016-3']);
  _gaq.push(['_setDomainName', 'none']);
  _gaq.push(['_setAllowLinker', true]);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
	
	
	
	
	var basket = new Array();
	var currencySymbol = "&pound;";
	$(document).ready(function() {
		/*$.get('/_ajax/get_currencySymbol.cfm',{rand:Math.random()},function(data) {
			currencySymbol = data;																	
		});*/
		
		
			
		$('.miniMinus,.largeMinus').live('mouseover mouseout',function(event) {
			if (event.type == 'mouseover') {
				$('img',this).attr('src','/images/on_minus.gif');	
			} else {
				$('img',this).attr('src','/images/off_minus.gif');	
			}									  
		});
		$('.miniPlus,.largePlus').live('mouseover mouseout',function(event) {
			if (event.type == 'mouseover') {
				$('img',this).attr('src','/images/on_plus.gif');	
			} else {
				$('img',this).attr('src','/images/off_plus.gif');	
			}									  
		});
		
		if ($('#navTypeForm').length) {
			$('#toggleBooks_AtoZ').click(function() {
				$.get('/_ajax/set_navStyle.cfm',{rand:Math.random(),type:'AtoZ'},function(data) {
					$('#titlesNav').html(data);																	  
				});									  
			});
			$('#toggleBooks_byCategory').click(function() {
				$.get('/_ajax/set_navStyle.cfm',{rand:Math.random(),type:'byCategory'},function(data) {
					$('#titlesNav').html(data);															  
				});									  
			});
		}
		$('#viewBasketLink').click(openBasket);
		if ($('#detailImage').length) {
			$('#detailImage').fancybox({titleShow:false});
		}
		if ($('a.productLookInside').length) {
			$('a.productLookInside').fancybox({
					  'titlePosition' : 'over',
					  'titleFormat' : function(title, currentArray, currentIndex, currentOpts) {
							return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + '</span>';
						} 
			});
		}
		if ($('.currencyLinks').length) {
			$('.currencyLinks').click(function() {
				var currency = $('img',this).attr('alt');
				$.get('/_ajax/set_currency.cfm',{rand:Math.random(),currency:currency},function(data) {
					location.reload(true);																			
				});
			});
		}
		if ($('.loginRegistered').length) {
			$('#password').bind('keyup',function(event) {
				if (event.keyCode == 13) {
					chkLogin();	
				}
			});
		}
		if ($('#emailSubscribeLink').length) {
			$('#emailSubscribeLink').click(handleSubscription);
		}
		if ($('#discountCode').length) {
			$('#discountCode').bind('keyup',function(event) {
				if (event.keyCode == 13) {
					chkDiscount();	
				}
			});
			$('#discountCodeLink').bind('click',chkDiscount);
			if ($('.removeDiscount').length) {
				$('.removeDiscount').bind('click',removeDiscount);
			}
		}
		if ($('#fastfactsnewslink').length) {
			$('#fastfactsnewslink').fancybox({titleShow:false});
		}
		if ($('#addAddressLink').length) {
			$('#addAddressLink').bind('click',chkAddressForm);
			$('#country').bind('change',chkCountryState);
		}
		if ($('.addressForm').length) {
			$('.addressDelete').bind('click',addressDelete);
			$('.addressEdit').bind('click',addressEdit);
			$('input[name=billingAddress]').bind('click',highlightAddress);
			$('input[name=deliveryAddress]').bind('click',highlightAddress);
		}
		if ($('#categoriesAll').length) {
			$('#categoriesAll').bind('click',selCategories);
			$('input[name="categories"]').bind('click',chkCategoriesToggle);
		}
		if ($('#tAndCsTextLink').length) {
			$('#tAndCsTextLink').fancybox({titleShow:false});
		}
		if ($('.scoreLink').length) {
			setupScoring();
			$('#toggleDescriptionLink').bind('click',toggleTitleDescription);
		}
		if ($('#reviewsLink').length) {
			$('#reviewsLink').bind('click',function() {
				$.scrollTo('#reviewsDiv',1000);										
			});
		}
		$.getJSON('/_ajax/get_basket.cfm',{rand:Math.random()},function(data) {
			basket = data;
			handleBasket(basket,'','',1);
		});
		if ($.fancybox) {
			$('.overlay').fancybox({titleShow:false});	
			$('.youtube').click(function() {
					$.fancybox({
								   	titleShow:false,
									'href':this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
									'type': 'swf',
									'swf'			: {
			   	 						'wmode'		: 'transparent',
										'allowfullscreen'	: 'true'
									}
							});	
					return false;
			});
			
			
		}
		
	});
	
	
	
