MooTools.More={version:"1.2.4.4",build:"6f6057dc645fdb7547689183b2311063bd653ddf"};Fx.Scroll=new Class({Extends:Fx,options:{offset:{x:0,y:0},wheelStops:true},initialize:function(b,a){this.element=this.subject=document.id(b);
this.parent(a);var d=this.cancel.bind(this,false);if($type(this.element)!="element"){this.element=document.id(this.element.getDocument().body);}var c=this.element;
if(this.options.wheelStops){this.addEvent("start",function(){c.addEvent("mousewheel",d);},true);this.addEvent("complete",function(){c.removeEvent("mousewheel",d);
},true);}},set:function(){var a=Array.flatten(arguments);if(Browser.Engine.gecko){a=[Math.round(a[0]),Math.round(a[1])];}this.element.scrollTo(a[0],a[1]);
},compute:function(c,b,a){return[0,1].map(function(d){return Fx.compute(c[d],b[d],a);});},start:function(c,g){if(!this.check(c,g)){return this;}var e=this.element.getScrollSize(),b=this.element.getScroll(),d={x:c,y:g};
for(var f in d){var a=e[f];if($chk(d[f])){d[f]=($type(d[f])=="number")?d[f]:a;}else{d[f]=b[f];}d[f]+=this.options.offset[f];}return this.parent([b.x,b.y],[d.x,d.y]);
},toTop:function(){return this.start(false,0);},toLeft:function(){return this.start(0,false);},toRight:function(){return this.start("right",false);},toBottom:function(){return this.start(false,"bottom");
},toElement:function(b){var a=document.id(b).getPosition(this.element);return this.start(a.x,a.y);},scrollIntoView:function(c,e,d){e=e?$splat(e):["x","y"];
var h={};c=document.id(c);var f=c.getPosition(this.element);var i=c.getSize();var g=this.element.getScroll();var a=this.element.getSize();var b={x:f.x+i.x,y:f.y+i.y};
["x","y"].each(function(j){if(e.contains(j)){if(b[j]>g[j]+a[j]){h[j]=b[j]-a[j];}if(f[j]<g[j]){h[j]=f[j];}}if(h[j]==null){h[j]=g[j];}if(d&&d[j]){h[j]=h[j]+d[j];
}},this);if(h.x!=g.x||h.y!=g.y){this.start(h.x,h.y);}return this;},scrollToCenter:function(c,e,d){e=e?$splat(e):["x","y"];c=$(c);var h={},f=c.getPosition(this.element),i=c.getSize(),g=this.element.getScroll(),a=this.element.getSize(),b={x:f.x+i.x,y:f.y+i.y};
["x","y"].each(function(j){if(e.contains(j)){h[j]=f[j]-(a[j]-i[j])/2;}if(h[j]==null){h[j]=g[j];}if(d&&d[j]){h[j]=h[j]+d[j];}},this);if(h.x!=g.x||h.y!=g.y){this.start(h.x,h.y);
}return this;}});
Fx.Slide=new Class({Extends:Fx,options:{mode:"vertical"},initialize:function(B,A){this.addEvent("complete",function(){this.open=(this.wrapper["offset"+this.layout.capitalize()]!=0);
if(this.open&&Browser.Engine.webkit419){this.element.dispose().inject(this.wrapper);}},true);this.element=this.subject=$(B);this.parent(A);var C=this.element.retrieve("wrapper");
this.wrapper=C||new Element("div",{styles:$extend(this.element.getStyles("margin","position"),{overflow:"hidden"})}).wraps(this.element);this.element.store("wrapper",this.wrapper).setStyle("margin",0);
this.now=[];this.open=true;},vertical:function(){this.margin="margin-top";this.layout="height";this.offset=this.element.offsetHeight;},horizontal:function(){this.margin="margin-left";
this.layout="width";this.offset=this.element.offsetWidth;},set:function(A){this.element.setStyle(this.margin,A[0]);this.wrapper.setStyle(this.layout,A[1]);
return this;},compute:function(E,D,C){var B=[];var A=2;A.times(function(F){B[F]=Fx.compute(E[F],D[F],C);});return B;},start:function(B,E){if(!this.check(arguments.callee,B,E)){return this;
}this[E||this.options.mode]();var D=this.element.getStyle(this.margin).toInt();var C=this.wrapper.getStyle(this.layout).toInt();var A=[[D,C],[0,this.offset]];
var G=[[D,C],[-this.offset,0]];var F;switch(B){case"in":F=A;break;case"out":F=G;break;case"toggle":F=(this.wrapper["offset"+this.layout.capitalize()]==0)?A:G;
}return this.parent(F[0],F[1]);},slideIn:function(A){return this.start("in",A);},slideOut:function(A){return this.start("out",A);},hide:function(A){this[A||this.options.mode]();
this.open=false;return this.set([-this.offset,0]);},show:function(A){this[A||this.options.mode]();this.open=true;return this.set([0,this.offset]);},toggle:function(A){return this.start("toggle",A);
}});Element.Properties.slide={set:function(B){var A=this.retrieve("slide");if(A){A.cancel();}return this.eliminate("slide").store("slide:options",$extend({link:"cancel"},B));
},get:function(A){if(A||!this.retrieve("slide")){if(A||!this.retrieve("slide:options")){this.set("slide",A);}this.store("slide",new Fx.Slide(this,this.retrieve("slide:options")));
}return this.retrieve("slide");}};Element.implement({slide:function(D,E){D=D||"toggle";var B=this.get("slide"),A;switch(D){case"hide":B.hide(E);break;case"show":B.show(E);
break;case"toggle":var C=this.retrieve("slide:flag",B.open);B[(C)?"slideOut":"slideIn"](E);this.store("slide:flag",!C);A=true;break;default:B.start(D,E);
}if(!A){this.eliminate("slide:flag");}return this;}});
/*
---
description: Provides a fallback for the placeholder property on input elements for older browsers.

license:
  - MIT-style license

authors:
  - Matthias Schmidt (http://www.m-schmidt.eu)

requires:
  core/1.2.5: '*'

provides:
  - Form.Placeholder

...
*/
(function(){if(!this.Form){this.Form={}}var a=("placeholder" in document.createElement("input"));if(!("supportsPlaceholder" in this)&&this.supportsPlaceholder!==false&&a){this.Form.Placeholder=new Class({});return}this.Form.Placeholder=new Class({Implements:Options,options:{color:"#A9A9A9",clearOnSubmit:true},initialize:function(c,b){this.setOptions(b);this.element=$(c);this.placeholder=this.element.get("placeholder");this.original_color=this.element.getStyle("color");if(this.element.get("value")==""){this.element.setStyle("color",this.options.color);this.element.set("value",this.placeholder)}this.element.addEvents({focus:function(){if(this.element.get("value")==this.placeholder){this.element.set("value","");this.element.setStyle("color",this.original_color)}}.bind(this),blur:function(){if(this.element.get("value")==""){this.element.setStyle("color",this.options.color);this.element.set("value",this.placeholder)}}.bind(this)});if(this.element.getParent("form")&&this.options.clearOnSubmit){this.element.getParent("form").addEvent("submit",function(d){if(this.element.get("value")==this.placeholder){this.element.set("value","")}}.bind(this))}}})})();


/*
* ten.js begins
*/

window.addEvent('domready', function(){

	var container = $('container');

	if($("searchresults") || $("productpage")){
		hijackwishlist = function(){
			wishlistids = new Request.JSON({ method: "get", url: "account/wishlist-json.php?json"})
			.addEvent("success", function(j){
				if(j){
					wishlist_ids=JSON.decode(JSON.encode(j), false);
					Array.each(wishlist_ids, function(i){
						container.getElements("#wishlist-item-"+i).addClass("on")
						.removeProperty("data-id")
						.removeEvent("click")
						.addEvent("click", function(){
							window.location="/account/#wishlist";
						});
					});
				}
			})
			.send();
		};
		hijackwishlist();
	};

	pickprice = function(price_array, quantity, fallback){

		if(!price_array) return fallback;

		switch(true){
			case quantity > 99:
				unitprice = price_array["100"];
				break;
			case quantity > 49:
				unitprice = price_array["50"];
				break;
			case quantity > 24:
				unitprice = price_array["25"];
				break;
			case quantity > 9:
				unitprice = price_array["10"];
				break;
			case quantity > 4:
				unitprice = price_array["5"];
				break;
			case quantity < 5:
				unitprice = price_array["1"];
				break;
			default: fallback;
		}
		if(unitprice) return unitprice;
		return fallback;
	}
	
	toggleGiftwrap = function(btn, override){
		pane = btn.getParent(".basket-row").getElements(".giftwrappane")[0];
		valu = pane.getElements(".quantitywrapped")[0]
		
		
		if(pane.hasClass("hidden")){
			pane.toggleClass("hidden");
			valu.value = valu.get("data-initial-value");
		} else {
			cancelGiftwrap(btn, override);
		}
	}
	
	cancelGiftwrap = function(btn, override){
		pane = btn.getParent(".basket-row").getElements(".giftwrappane")[0];
		valu = pane.getElements(".quantitywrapped")[0]


		if(override!=true && override!=false){override=false; }
		
		quantity = valu.get("value");
		if(quantity==0 || override || pane.hasClass("hidden")){
			pane.addClass("hidden");
			if(valu.value!=0){
				valu.value=0;
				valu.set("data-initial-value",0);
			}
		} else {
			valu.focus();
		}
	}	
	
	calculateGiftwrappings = function(costper){
		
		if(!costper) costper=$(document.body).get("data-giftwrapcost");
		var q=0;
		Array.each(container.getElements(".quantitywrapped"), function(i){
			val = parseInt(i.value);
			if (!val) val = 0;
			q = q+val;
		});

		$("giftwrapquanity").set("html", q);
		$("giftwrapprice").set("html", (q * costper).toFixed(2));

	}
	
	if($("basket")){
	
		// just fire an update to check basket is correct
		new Request.JSON({ method: "post", url: "shop/update.php", data: {'justdoit':'true'} })
		.addEvent("success", function(j){
			
			if (j) {
				setBasketPostage(j.shipping);
				setBasketSubtotal(j.subtotal, "GBP");
				setBasketTotal(j.total, "GBP");
			}
		
		}).send();		

	
		//reveal stuff we want hidden without JS available
		
		if (container.getElements('table.basket .wrapping-clear-button')){
		  
	  		item_giftwrap_clear = container.getElements('table.basket .wrapping-clear-button');
					
					// find the input box related to this
					// set the input value to 0 and make sure the 'change' event has occured.
					
			item_giftwrap_clear.each(function(clearer){
						
				clearer.addEvent('click', function(ev){
	
					if (ev) ev.stop();
					p = clearer.getParent('.giftwrappane');
					p.getElement('input').set('value', 0).fireEvent('change');
					p.getElement('a.wrapping-cancel-button').fireEvent('click');
					
				});
			});
		}

 		if(els=container.getElements("#giftwrap", "#giftwrap-pad", ".giftwrapbtn")){
 			els.each(function(d){
	 			d.removeClass("hidden");
 			});
 		};
		
		container.getElements(".basket .giftwrapbtn")
		.addEvent("click", function(){
			toggleGiftwrap(this, false);	//this.getParent(".basket-row").getElements(".giftwrappane")[0].toggleClass("hidden");
		});
		
		container.getElements(".basket .wrapping-cancel-button")
		.addEvent("click", function(){
			cancelGiftwrap(this, true);
			return false;
		});
		
		container.getElements(".basket .quantitywrapped")
		.addEvent("change", function(){
			calculateGiftwrappings();
			target = this.getParent(".basket-row").getElement(".row-quantity");
			if(target.value < parseInt(this.value)){
				this.value = target.value;
			}
			if (this.getParent('.basket-row').getElement('.giftwrapquantity')){
				this.getParent('.basket-row').getElement('.giftwrapquantity').set('html', this.value);
			}
			target.fireEvent("blur");
		})
		.addEvent("keyup", function(){
			this.fireEvent("change");
		});
				
		container.getElements(".basket .remove-giftwrapping")
		.addEvent("click", function(ev){
			if (ev) ev.stop();
			container.getElements(".basket .quantitywrapped").each(function(i){
				cancelGiftwrap(i, true);
			});
			calculateGiftwrappings();
		});
		
		if (donation_input = container.getElement('.basket .charity-gift-value')){
		
		
				paren = donation_input.getParent('.donationrow');
		
				if (paren && paren.getElement('.charity-campaign-name')){
				
						paren.getElement('.remove-donation')
						.removeClass('hidden')
						.addEvent('click', function(ev) {
							if (ev) ev.stop();
							
							donation_input.value=0;
							donation_input.fireEvent('blur');
						});
						

						donation_input
						.addEvent('blur', function(ev){
						
								if (ev) ev.stop();
								
								// fetch the value of the new donation
								value = donation_input.value;
								campaign = donation_input.getParent('.donationrow').getElement('.charity-campaign-name').value;
								
								donation_input.set('value', (1.0 * donation_input.value).toFixed(2));

								// send the value of the new donation to the basket
								new Request.JSON({ method: "post", url: "shop/update.php", data: {'campaign':campaign, 'donation':value} })
								.addEvent("success", function(j){

									if (j) {
										setBasketPostage(j.shipping);
										setBasketSubtotal(j.subtotal, "GBP");
										setBasketTotal(j.total, "GBP");
									}
													
								})
								.send();		
								
						})
				};
		}
		
		container.getElements(".basket tr input.row-quantity")
		.addEvent("blur", function(){
			
			if (this.hasClass("vouchers")){ // || this.hasClass("charity-gift-value")
				return false;
			} 

			setSpinner($("basket-total-value"));

			// ensure value is a number
			val = parseInt(this.get("value"));
			if (!val) val = 1;
			
			// fire the gift wrap calculation again here (to check quantity wrapped < row quantity)
			if (val < this.getParent(".basket-row").getElements(".quantitywrapped")[0].value){
				this.getParent(".basket-row").getElements(".quantitywrapped")[0].value = val;
				this.getParent(".basket-row").getElements(".quantitywrapped")[0].fireEvent('keyup');
			}

			// update value
			data = {
				item : this.getProperty("data-item"),
				quantity : val,
				quantitywrapped : this.getParent(".basket-row").getElements(".quantitywrapped")[0].value
			};
			
			// console.log(this.get("data-prices"));
						
			price_array = JSON.decode(this.get("data-prices"));
			
			// work out unit price
			single_unit_price = (this.get("data-unit-price")) ? this.get("data-unit-price") : price_array[0];
			unitprice = pickprice(price_array, val, single_unit_price);
			try { unitprice = unitprice.toFixed(2); } catch(e){ }

			this.getParent("tr").getElements(".price-per")[0].set("html", "Per copy: &pound;" + unitprice);
			
			// work out row total
			var rowtotal = (val * unitprice).toFixed(2);
			this.getParent("tr").getChildren(".row-total").set("html", "&pound;" + rowtotal);
			
			// update session
			new Request.JSON({ secure: false, method: "post", url: "shop/update.php", data: data })
			.addEvent("success", function(j){
			
				if (j) {
					if (voucher_checker_updater = container.getElement('#voucher-checker-a')) voucher_checker_updater.fireEvent('click');
					setBasketPostage(j.shipping);
					setBasketSubtotal(j.subtotal, "GBP");
					setBasketTotal(j.total, "GBP");
				}
								
			})
			.send();
		
		})
		.addEvent('blur', function(){
			if (this.hasClass("vouchers") || this.hasClass("charity-gift-value")){
				return false;
			} 

			// on blur re-set the value
			val = parseInt(this.get("value"));
			if (!val) val = 1;
			
			// set value
			this.set("value", val);
			
			// update max value of related wrappingquantity field
			wrapelem=this.getParent(".basket-row").getElements(".quantitywrapped")[0];
			wrapelem.set("max", val);
			if(wrapelem.get("max")<wrapelem.value){
				wrapelem.value=wrapelem.get("max");
			}
			calculateGiftwrappings();
			
		});

		$("charity-gift-value")
		.addEvent("focus", function(){
			value = this.get("data-value");
			this.set("value",value);
		})
		.addEvent("blur", function(){
			value = this.get("value");
			this.set("data-value",value);
			this.set("value",""+Math.round(value*100)/100);
		});
	}
	

	
	if($("currencyconvert")){

		ep = new Element('span', { 
			html: '<select id="currencyselect" name="currencies"><option value="GBP" selected>&pound; GBP</option><option value="EUR">&euro; EUR</option><option value="USD">$ USD</option></select>'
		}).addClass('action-text');
		
		if(false) { // requested to be removed by Ben Bedford 19/11/2011 email to DL.

			$("currencyconvert")
				.removeClass("plain")
				.adopt(ep);
	
			$("currencyconvert")
				.setProperty("data-fromcurrency","GBP")
				.setProperty("data-tocurrency","USD")
				.setProperty("data-originalamount", $("basket-total-value").get("html"))
				.setProperty("data-originalcurrency", "GBP");
				
			$("currencyselect")
				.addEvent('change', function(){ 	//i want to know the exchange rate value for my currency, please.

					var c = $("currencyconvert"),
						s = $("currencyselect"),
						v = $("basket-total-value"),
						val = v.getProperty("data-value");
					
					setSpinner(v);
					
					exchangerate = new Request.JSON({ 
						url: 'shop/currency-json.php?from='+c.getProperty("data-fromcurrency")+'&to='+s.value+'&val='+val+'',
						method: 'get' 
					})
					.addEvent('success', function(j){

						if(j) setBasketSubtotal(j.exchange, val);
						unsetSpinner(v, false);

					}).send();
				}
			);
		}
	}
	
	container.getElements(".wishlist-hook")
	.addEvent('click', function(){
		if(!this.getProperty("data-id")){ return false; }
		product_id = this.getProperty("data-id");
		var t= this;
		setSpinner(t);
		req = new Request.JSON({ url: 'wishlist.php?add='+product_id, method: 'get'})
		.addEvent('success', function(j){
			msg = '';
			if(j){
				msg = "Added to wishlist!";

				t.addClass("on")
				.removeProperty("data-id")
				.removeEvent("click")
				.addEvent("click", function(){
					window.location="/account/#wishlist";
				})
			} else {
				msg = "Unknown problem. Try again.";
			}
			
			unsetSpinner(t, msg);
			
		})
		.send();
		return false;
	});
	
	
	container.getElements(".wishlist-remove-hook")
	.addEvent('click', function(){
		if(!this.getProperty("data-id")){return false;} 
		product_id= this.getProperty("data-id");
		var t=this;
		setSpinner(t);
		req = new Request.JSON({ url: 'wishlist.php?remove='+product_id, method: 'get'})
		.addEvent('success', function(j){
			if(j){
				unsetSpinner(t, "Removed!");
				t.removeProperty("data-id");
			} else {
				unsetSpinner(t, "Unknown problem. Try again.");
			}
		})
		.send();
		return false;
	});


    if (container.getElement('.promo-cycle')){
        var
            clickerContainer = $('container').getElement('.promo-clickers'),
            cels = clickerContainer.getChildren('li'),
            
            cycleContainer = $('container').getElement('.promo-cycle'),
            xels = cycleContainer.getChildren('li'),
            xpos = 0,
            
            rotating = false,
            
            turnoff = function (index){
                cels.each(function(el){
                	el.removeClass('on').setStyle('background-color', '#EBEBDC');
                });
                if (index===false){
                    xels.each (function (el, i){
                        xels[i].morph({'opacity':'0', 'background-color':'#000', 'height': xels[i++].getStyle('height')}).removeClass("on"); 
                    });
                } else {
                    xels[index].morph({'opacity':'0', 'background-color':'#000', 'height': xels[index++].getStyle('height')}).removeClass("on"); 
                }
            }
            
            turnon = function (index){
                if (index!==false){
                    xels[index].setStyle('height', 'auto').morph({'opacity':'1'}).addClass("on"); 
                    cels[index].setStyle('height', 'auto').addClass("on").setStyle('background-color', '#9FC26F'); 
                }
            }
            
            rotateBanners = function (){

                if (rotating){
                    xcurr = xpos%xels.length;
                    xnext = ++xpos%xels.length;
                    
                    turnoff(xcurr);
                    turnon(xnext);
                }
                                
            }
        
        cels.each(function(el){
            el.addEvent('click', function(ev){
                if (ev) ev.stop();
                
                try {
                	$clear(goGoRotateBanners);
    				goGoRotateBanners = rotateBanners.periodical(10000);
                } catch (e){
                
                }
                
                rotating = false;
                
                turnoff(false);
                turnon(this.getAllPrevious('li').length);
                
                rotating = true;
                
            })
        });
        
        xels.each(function(el){
            if (!el.hasClass('on')){
                el.setStyle('opacity', 0);
            } else {
                // keep visible
            }
        });
        
        rotating = true;
    	goGoRotateBanners = rotateBanners.periodical(10000);
    }

	// previewbox?
	if ($('container').getElement('.overscroller')){
	
			// there's a window load call to get size of image and set width of li
			window.addEvent('load', function(){

				// set width of each li
				$('scrollee').getElements('li')
				.each(function(l){
					l.setStyle('width', l.getElement('img').getSize().x);
				});

				// magic					
				is = new InfiniteScroll($('scrollee'));
				
				// next/previous
				$('container').getElement('.previewbox .back')
				.addEvent('click', function(ev){
							
					if (ev) ev.stop();
					is.previous();
				
				});
				
				$('container').getElement('.previewbox .fwd')
				.addEvent('click', function(ev){
				
					if (ev) ev.stop();
					is.next();
				
				});
			});
				
		// on load so we get image sizes
		//window.addEvent('load', function(){

	};
	
	window.addEvent('resize', function(){
	
		if (window.getSize().y > $('container').getElement('.white').getSize().y){
			$('container').getElement('.white').setStyle('height', window.getSize().y);
		}
	
	});
	
	window.addEvent('load', function(){
		window.fireEvent('resize');
	});
	
	// left hand column mouse styles
	container.getElements('.left .cats li')
	.addEvent('mouseenter', function(){
	
		// not on shadows
		if (this.hasClass('shadow')) return;
		
		// change background colour
		this.tween('background-color', '#9FC26F');
		if (this.getPrevious('li') && this.getPrevious('li').hasClass('shadow')) this.getPrevious('li').tween('background-color', '#9FC26F');
		
	})
	.addEvent('mouseleave', function(){
	
		// not on shadows
		if (this.hasClass('shadow')) return;
		
		// change background colour
		this.tween('background-color', this.getProperty('data-back'));
		if (this.getPrevious('li') && this.getPrevious('li').hasClass('shadow')) this.getPrevious('li').tween('background-color', this.getProperty('data-back'));
		
	})
	.addEvent('click', function(ev){
	
		// handle click
		if (ev){
			if (document.id(ev.target).get('tag') != 'a'){
				if (document.id(ev.target).getElement('a')){
					location.href = this.getElement('a').getProperty('href');
				}
			}
		}
	
	})
	.each(function(el){
		// set background colour
		el.setProperty('data-back', el.getStyle('background-color'))
	});
	
	
	// top 10
	if(container.getElement('.top10 li')) {
	
		container.getElements('.top10 a')
		.addEvent('click', function(ev){
		
			if (ev){
			
				ev.stop();
				try { 
					$clear(top10Rotator); 
					top10Rotator = top10rotate.periodical(6000);
				} catch(e){ };
				
			}
			
			var s = this.getParent('li').getAllPrevious('li').length;
			
			container.getElements('.top10 li').removeClass('selected');
			this.getParent('li').addClass('selected');
			
			container.getElements('.top10output li').tween('opacity', 0);
			container.getElements('.top10output li')[s].get('tween').cancel();
			container.getElements('.top10output li')[s].tween('opacity', 1);
		
		});
		
		// grab and click the first element
		container.getElement('.top10 li').addClass('selected').getChildren('a').fireEvent('click');
	
		top10rotate = function(){
	
			els = container.getElements('.top10 li');
			sel = container.getElement('.top10 li.selected');
			c = sel.getAllPrevious('li').length;
			
			c++;
			
			if (c >= els.length) c = 0;
			
			els.removeClass('selected');
			els[c].addClass('selected');
			els[c].getElement('a').fireEvent('click');
		}
		
		if(container.getElement('.top10')){
			top10Rotator = top10rotate.periodical(6000);
		}
	     
	}
	  /* end top 10 */


	
	
	// autocompleter
	autocompleter = new Request.JSON({ url: '/products/json.php', method: 'get' })
	.addEvent('success', function(j){
		if (j){
		
			// empty our results
			el = $('frm-autocomplete').getNext('ul.results').setStyle('display', 'block').empty();
			
			// value
			val = j.val;
			
			// books
			el.adopt(new Element('li', { html: '<span class="title">Books</span>' + (j.books.length == 0 ? ' - no results found' : ' (' + j.books.length +')' )  }));
			
			// loop over books
			$each(j.books, function(j){
				j.t = j.t.replace(val, '<span class="r">' + val + '</span>');
				el.adopt(new Element('li', { html: (j.l != '' ? '<a href="/products/' + j.l + '">' : '') + j.t + (j.l != '' ? '</a>' : '') }));			
			});
			
			// categories
			el.adopt(new Element('li', { html: '<span class="title">Categories</span>' + (j.cats.length == 0 ? ' - no results found' : ' (' + j.cats.length +')') }));
			
			// loop over cats
			$each(j.cats, function(j){
				j.t = j.t.replace(val, '<span class="r">' + val + '</span>');
				el.adopt(new Element('li', { html: (j.l != '' ? '<a href="/category/' + j.l + '">' : '') + j.t + (j.l != '' ? '</a>' : '') }));			
			});
		}
	});
	
	// autocomplete
	$('frm-autocomplete').getElement('input[type="text"]')
	.addEvent('keyup', function(ev){
		autocompleter.send('&query='+this.get('value'));
	})
	.addEvent('blur', function(ev){
		(function(){ $('frm-autocomplete').getNext('ul.results').setStyle('display', 'none'); }.delay(150));
	})
	.setProperty('autocomplete', 'off');
	
	// add to basket widget function	
	setBasketWidgetPrices = function(widget){

		
		price_array = JSON.decode(widget.getParent('.buy').get("data-prices"), false);
		quantity = widget.get("value");

		unitprice = pickprice(price_array, quantity, widget.get("data-cost"));
		try { unitprice = unitprice.toFixed(2); } catch(e){ };
		
/* 		if(!unitprice){unitprice = widget.get("data-cost")} */
		
		if(!quantity) quantity=1;
		
		//TODO DISCOUNT CALCULATION
		
		value=(unitprice*quantity).toFixed(2);
		
		widget.getParent(".buy").getElement(".product-individual-price").set("html", unitprice);
		widget.getParent(".buy").getElement(".product-quantity-price").set("html",value);
		widget.getParent(".buy").setProperty("data-cost",unitprice);   
	};
	
	// add to all add to basket instances
	container.getElements(".widget-product-quantity")
	.each(function(el){
	
		el.addEvent("keyup", function(){
			setBasketWidgetPrices(this);
		});
	
		setBasketWidgetPrices(el);
	});
	
	// need to add an action to the add to basket function
	
	
	container.getElements('.addto')
	.addEvent('click', function(ev){
		
		if (ev) ev.stop();
		buy = this.getParent('.buy');
		
		new Request.JSON({
			method: 'post',
			url: 'addtobasket.php',
			data: {
				productid : buy.get('data-id'),
				title  : buy.get('data-title'),
				summary  : buy.get('data-summary'),
				unitprice  : parseFloat(buy.get('data-cost')), 
				quantity : ($('widget-product-quantity')) ? parseFloat($('widget-product-quantity').get('value')) : 1,
				pricearray : buy.get("data-prices"),
				vatcharged : buy.get("data-vatcharged"),
				extracols : buy.get('data-extracols')
			}
		})
		.addEvent('success', function(j){

			if (j) window.location = '/basket.php';

		})
		.send();
	});
	
	container.getElements('li.alsoboughtitem').addEvent('click', function(b){
		location.href = this.getProperty('data-href');
	});

    if (Form.Placeholder){
        Array.each( $('container').getElements('input, textarea'), function(x){
            if(x.getProperty('placeholder')){
                new Form.Placeholder(x);
            }
        });
    }
    
  if (address_chooser = $('container').getElement('.basket-address-selector select')){
  	
  		address_chooser.addEvent('change', function(ev){
  			
  				if (ev) ev.stop();
  				
  				if (address_chooser.value=='-1'){
  						window.location = "/account/delivery.php?return=/shop/basket.php"; 
  				} else {
		  				window.location = "/shop/basket.php?addressid=" + address_chooser.value;
		  		}
  		});
  		
  	
  }
  
  if (upsell_products = $('container').getElements('.upselling .product')){
  		
  		upsell_products.each(function(up){

  				var guid;	// necessary to re-set score each time.
  			
					if (guid = up.getProperty('data-guid')){
  						up
  						.addClass('clickable')
		  				.addEvent('click', function(ev){
  					
  								if (ev) ev.stop();
  								window.location = guid;
  							
		  				});
		  		}
  		});
  		
  }
  
	if (voucher_checker = $('container').getElement('tr.promocode.checker')){

			// create an a element for clickability
			// > '<a href="#addvoucher">Add</a>'
			
			code_input = voucher_checker.getElement('input.vcode');
			
			el = new Element('a', {
				href: '#addvoucher',
				html: 'check voucher',
				id: 'voucher-checker-a',
				events: {

					// attach action to the link
					// do a async request to fetch the data from
					// > http://www.10ofthose.com/shop/checkvoucher-json.php?u={USERID}&code={CODE}

					click: function(){

						uid = voucher_checker.getElement('input.uid').value;
						vcode = code_input.value;
						discountable_total = $('basket-total-final-value').getProperty('data-value'); // TODO - check this updates
						
						// what url to request from?
						req_url = "shop/checkvoucher-json.php?json&u="+uid+"&code="+vcode;
						
						new Request
						.JSON({ method: "get", url: req_url})
						.addEvent("success", function(j){
							if(j){
							
								voucher = JSON.decode(JSON.encode(j));
								
								if (voucher.valid){
								
									data = JSON.decode(voucher.data);

									totals = voucher.totals;
									
									// work out how much money should be taken off the total while not running into negative figures

									value_applicable = totals.applieddiscount;
									value_applicable = (Math.round(value_applicable*100)/100).toFixed(2);
									
									// add a row below detailing the discount provided by the voucher code

									if (totals.applieddiscount < JSON.decode(voucher.data).DiscountValue) {
										note = 'Discount code saved (your voucher was worth less than the basket by £'+(Math.round((JSON.decode(voucher.data).DiscountValue-totals.applieddiscount)*100)/100).toFixed(2)+' - any credit not used will be lost)';
									} else {
										note = 'Discount code saved (this will be applied to checkout)';
									}
									
									if ($('deleteablevoucherrow')){
										$('deleteablevoucherrow').destroy();
									}

									row = new Element('tr', {
										'class': 'voucherrow',
										'id':'deleteablevoucherrow',
										html: '<td colspan="2">'+note+'</td>'
										+'<td class="price-column-entry">&pound;-'+ value_applicable +'</td>'
										+'<td class="plain">&nbsp;</td>'
									});
									
									row.inject(voucher_checker, 'after');
									
									code_input.setStyle('border', '1px solid rgb(40,140,40)');
									
									button_holder
									.removeClass('r') // unstyle TD
									.addClass('plain');
									button_holder
									.getElement('a')	// make button hide 
									.set('html',''); 
									
									// update the total price
									total = totals.total;
									setBasketTotal(total,'GBP');

								} else {
								
									code_input.setStyle('border', '1px solid rgb(255,10,10)');
								
								}
							}
						})
						.send();
						
						return false;
					}
				}
			});
			
			// make the child td.plain td.r
			// > '<td class="r">&nbsp;</td>'
			button_holder = voucher_checker.getElement('td.plain');
			
			// attach the link from before
			button_holder
			.removeClass('plain')
			.addClass('r')
			.set('html', '')
			.adopt(el);
			
	}

});

function setBasketTotal($value, $currency) {
	if ($("basket-total-final-value")) {
			$("basket-total-final-value").set("html", "" + $value);
			$("basket-total-final-value").setProperty("data-value", $value);
			
			if($("currencyselect") && $currency=="GBP"){
			
				$("basket-total-final-value").set("html", "&pound;" + $value);
				
			}
	}
}

function setBasketPostage(value){

	$("delivery-value")
	.set("html", "" + value)
	.setProperty("data-value", "" + value);

}

function setBasketSubtotal($value, $currency){
	if(!$currency) $currency="GBP";

	$("basket-total-value").set("html", "" + $value);

	if($("currencyselect") && $currency=="GBP"){
	
		$("basket-total-value").set("html", "&pound;" + $value);
		$("currencyselect").selectedIndex=0;
		$("basket-total-value").setProperty("data-value", $value);
		$("currencyconvert").setProperty("data-originalamount", $value);
	}
}

function setSpinner($dom){
	$dom.set("html", "<img style='text-align:center' src='images/ajax-loader.gif' alt='this is temporary' height='16' width='16' />");
}

function unsetSpinner($dom, html){
	if(html) $dom.set("html", html+"&nbsp;"); //else nothing
}

function checkVoucherValid(uid,vcode){
	data = new Array(uid,vcode);
	return data;
}
