/*******************
 * Code: On loading of document
 * Description: Prepare language selection box.
 ******************/
window.addEvent('domready',function(){
	// Prepare language selection
		var lang_select_hidden = true;
		if($chk($('lang'))){
			$('lang').addEvent('mouseenter', function(){if(lang_select_hidden){$('languages_menu').show();$('languages_menu').fade(0.9);lang_select_hidden = false;}});
			$('languages_menu').addEvent('mouseleave', function(){if(!lang_select_hidden){$('languages_menu').fade(0);(function(){lang_select_hidden = true; $('languages_menu').hide();}).delay(500);}});
			$('languages_menu').fade(0);
		}
});

/*******************
 * Class: Slimbox
 * Description: This class handles the lightbox clone.
 * Usage: see docs!
 ******************/
var Slimbox=(function(){var F=window,n=Browser.Engine.trident4,u,g,G=-1,o,w,E,v,y,M,s,m={},t=new Image(),K=new Image(),I,a,h,q,J,e,H,c,A,L,x,i,d,C;F.addEvent("domready",function(){$(document.body).adopt($$(I=new Element("div",{id:"lbOverlay",events:{click:D}}),a=new Element("div",{id:"lbCenter"}),H=new Element("div",{id:"lbBottomContainer"})).setStyle("display","none"));h=new Element("div",{id:"lbImage"}).injectInside(a).adopt(q=new Element("div",{styles:{position:"relative"}}).adopt(J=new Element("a",{id:"lbPrevLink",href:"#",events:{click:B}}),e=new Element("a",{id:"lbNextLink",href:"#",events:{click:f}})));c=new Element("div",{id:"lbBottom"}).injectInside(H).adopt(new Element("a",{id:"lbCloseLink",href:"#",events:{click:D}}),A=new Element("div",{id:"lbCaption"}),L=new Element("div",{id:"lbNumber"}),new Element("div",{styles:{clear:"both"}}))});function z(){var N=F.getScroll(),O=F.getSize();$$(a,H).setStyle("left",N.x+(O.x/2));if(v){I.setStyles({left:N.x,top:N.y,width:O.x,height:O.y})}}function l(N){["object",n?"select":"embed"].forEach(function(P){Array.forEach(document.getElementsByTagName(P),function(Q){if(N){Q._slimbox=Q.style.visibility}Q.style.visibility=N?"hidden":Q._slimbox})});I.style.display=N?"":"none";var O=N?"addEvent":"removeEvent";F[O]("scroll",z)[O]("resize",z);document[O]("keydown",p)}function p(O){var N=O.code;return u.closeKeys.contains(N)?D():u.nextKeys.contains(N)?f():u.previousKeys.contains(N)?B():false}function B(){return b(w)}function f(){return b(E)}function b(N){if(N>=0){G=N;o=g[N][0];w=(G||(u.loop?g.length:0))-1;E=((G+1)%g.length)||(u.loop?0:-1);r();a.className="lbLoading";m=new Image();m.onload=k;m.src=o}return false}function k(){a.className="";d.set(0);h.setStyles({backgroundImage:"url("+o+")",display:""});q.setStyle("width",m.width);$$(q,J,e).setStyle("height",m.height);A.set("html",g[G][1]||"");L.set("html",(((g.length>1)&&u.counterText)||"").replace(/{x}/,G+1).replace(/{y}/,g.length));if(w>=0){t.src=g[w][0]}if(E>=0){K.src=g[E][0]}M=h.offsetWidth;s=h.offsetHeight;var P=Math.max(0,y-(s/2)),N=0,O;if(a.offsetHeight!=s){N=i.start({height:s,top:P})}if(a.offsetWidth!=M){N=i.start({width:M,marginLeft:-M/2})}O=function(){H.setStyles({width:M,top:P+s,marginLeft:-M/2,visibility:"hidden",display:""});d.start(1)};if(N){i.chain(O)}else{O()}}function j(){if(w>=0){J.style.display=""}if(E>=0){e.style.display=""}C.set(-c.offsetHeight).start(0);H.style.visibility=""}function r(){m.onload=$empty;m.src=t.src=K.src=o;i.cancel();d.cancel();C.cancel();$$(J,e,h,H).setStyle("display","none")}function D(){if(G>=0){r();G=w=E=-1;a.style.display="none";x.cancel().chain(l).start(0)}return false}Element.implement({slimbox:function(N,O){$$(this).slimbox(N,O);return this}});Elements.implement({slimbox:function(N,Q,P){Q=Q||function(R){return[R.href,R.title]};P=P||function(){return true};var O=this;O.removeEvents("click").addEvent("click",function(){var R=O.filter(P,this);return Slimbox.open(R.map(Q),R.indexOf(this),N)});return O}});return{open:function(P,O,N){u=$extend({loop:false,overlayOpacity:0.8,overlayFadeDuration:400,resizeDuration:400,resizeTransition:false,initialWidth:250,initialHeight:250,imageFadeDuration:400,captionAnimationDuration:400,counterText:"{x}/{y}",closeKeys:[27,88,67],previousKeys:[37,80],nextKeys:[39,78]},N||{});x=new Fx.Tween(I,{property:"opacity",duration:u.overlayFadeDuration});i=new Fx.Morph(a,$extend({duration:u.resizeDuration,link:"chain"},u.resizeTransition?{transition:u.resizeTransition}:{}));d=new Fx.Tween(h,{property:"opacity",duration:u.imageFadeDuration,onComplete:j});C=new Fx.Tween(c,{property:"margin-top",duration:u.captionAnimationDuration});if(typeof P=="string"){P=[[P,O]];O=0}y=F.getScrollTop()+(F.getHeight()/2);M=u.initialWidth;s=u.initialHeight;a.setStyles({top:Math.max(0,y-(s/2)),width:M,height:s,marginLeft:-M/2,display:""});v=n||(I.currentStyle&&(I.currentStyle.position!="fixed"));if(v){I.style.position="absolute"}x.set(0).start(u.overlayOpacity);z();l(1);g=P;u.loop=u.loop&&(g.length>1);return b(O)}}})();
// AUTOLOAD CODE BLOCK (MAY BE CHANGED OR REMOVED)
Slimbox.scanPage = function() {
	$$("a").filter(function(el){ return el.rel && el.rel.test(/^lightbox/i);}).slimbox({/* Put custom options here */}, null, function(el) {
		return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
	});
};
if (!/android|iphone|ipod|series60|symbian|windows ce|blackberry/i.test(navigator.userAgent)) window.addEvent("domready", Slimbox.scanPage);

/*******************
 * Class: MooDialog & rel=popup
 * Description: displays nice popup
 * Usage: <a href='http://www.asdf.com/' rel='popup'>asdf!</a>
 ******************/
var Overlay=new Class({Implements:[Options,Events],options:{id:"overlay",color:"#000",duration:500,opacity:0.5,zIndex:5000},initialize:function(a,b){this.setOptions(b);this.container=document.id(a);if(Browser.Engine.trident&&Browser.Engine.version<=6){this.ie6=true}this.bound={window:{resize:this.resize.bind(this),scroll:this.scroll.bind(this)},overlayClick:this.overlayClick.bind(this),tweenStart:this.tweenStart.bind(this),tweenComplete:this.tweenComplete.bind(this)};this.build().attach()},build:function(){this.overlay=new Element("div",{id:this.options.id,opacity:0,styles:{position:(this.ie6)?"absolute":"fixed",background:this.options.color,left:0,top:0,"z-index":this.options.zIndex}}).inject(this.container);this.tween=new Fx.Tween(this.overlay,{duration:this.options.duration,link:"cancel",property:"opacity"});return this}.protect(),attach:function(){window.addEvents(this.bound.window);this.overlay.addEvent("click",this.bound.overlayClick);this.tween.addEvents({onStart:this.bound.tweenStart,onComplete:this.bound.tweenComplete});return this},detach:function(){var a=Array.prototype.slice.call(arguments);a.each(function(b){if(b=="window"){window.removeEvents(this.bound.window)}if(b=="overlay"){this.overlay.removeEvent("click",this.bound.overlayClick)}},this);return this},overlayClick:function(){this.fireEvent("click");return this},tweenStart:function(){this.overlay.setStyles({width:"100%",height:this.container.getScrollSize().y});return this},tweenComplete:function(){this.fireEvent(this.overlay.get("opacity")==this.options.opacity?"show":"hide");return this},open:function(){this.fireEvent("open");this.tween.start(this.options.opacity);return this},close:function(){this.fireEvent("close");this.tween.start(0);return this},resize:function(){this.fireEvent("resize");this.overlay.setStyle("height",this.container.getScrollSize().y);return this},scroll:function(){this.fireEvent("scroll");if(this.ie6){this.overlay.setStyle("left",window.getScroll().x)}return this}});
var MooDialog=new Class({Implements:[Options,Events],options:{size:{width:300,height:100},offset:{x:0,y:-100},title:null,scroll:true,useEscKey:true,disposeOnClose:true,closeButton:true,closeOnOverlayClick:true,useScrollBar:true,fx:{type:"tween",open:1,close:0,options:{property:"opacity",duration:400}}},initialize:function(b){this.setOptions(b);this.ie6=Browser.Engine.trident&&Browser.Engine.version<=4;var b=this.options,c=b.size,a=c.width,f=c.height,e=this.wrapper=new Element("div",{"class":"MooDialog",styles:{width:a,height:f,position:b.scroll&&!this.ie6?"fixed":"absolute","z-index":6000,opacity:0}}).inject(document.body);this.content=new Element("div",{styles:{width:a,height:f,overflow:b.useScrollBar?"auto":"hidden"}}).inject(e);if(b.title){this.title=new Element("div",{"class":"title",text:b.title}).inject(e);e.addClass("MooDialogTitle")}if(b.closeButton){this.closeButton=new Element("a",{"class":"close",events:{click:this.close.bind(this)}}).inject(e)}var d=document.id(document.body).getSize();this.setPosition((d.x-a)/2,(d.y-f)/2);if(b.scroll&&this.ie6){window.addEvent("scroll",function(g){this.setPosition((d.x-a)/2,(d.y-f)/2)}.bind(this))}if(!this.fx){this.fx=b.fx.type=="morph"?new Fx.Morph(e,b.fx.options):new Fx.Tween(e,b.fx.options)}this.fx.addEvent("complete",function(){this.fireEvent(this.open?"show":"hide");if(b.disposeOnClose&&!this.open){this.dispose()}}.bind(this));this.overlay=new Overlay(document.body,{duration:this.options.fx.options.duration});if(b.closeOnOverlayClick){this.overlay.addEvent("click",this.close.bind(this))}},setContent:function(a){this.content.empty();switch($type(a)){case"element":this.content.adopt(a);break;case"string":case"number":this.content.set("text",a);break}return this},setPosition:function(b,e){var c=this.options,d=this.wrapper;b+=c.offset.x;e+=c.offset.y;b=b<10?10:b;e=e<10?10:e;if(d.getStyle("position")!="fixed"){var a=document.id(document.body).getScroll();b+=a.x;e+=a.y}d.setStyles({left:b,top:e});return this},open:function(){this.open=true;this.fireEvent("open");this.fx.start(this.options.fx.open);this.overlay.open();if(this.options.useEscKey){document.id(document.body).addEvent("keydown",function(a){if(a.key=="esc"){this.close()}}.bind(this))}return this},close:function(){this.open=false;this.fireEvent("close");this.fx.start(this.options.fx.close);this.overlay.close();return this},dispose:function(){this.wrapper.destroy();this.overlay.overlay.destroy()},toElement:function(){return this.wrapper}});Element.implement({MooDialog:function(a){var b=new MooDialog(a).setContent(this).open();this.store("MooDialog",b);return this}});
MooDialog.Iframe=new Class({Extends:MooDialog,initialize:function(b,a){this.parent(a);a=this.options,optionsSize=a.size;this.setContent(new Element("iframe",{src:b,frameborder:0,scrolling:a.useScrollBar?"auto":"no",width:optionsSize.width,height:optionsSize.height})).open()}});
window.addEvent("domready", function(){$$('a[rel=popup]').each(function(el){el.addEvent('click', function(){ var d = new MooDialog.Iframe(el.get('href'),{size:{width:800,height:600}}); return false; })});});

/*******************
 * Class: dnCart
 * Description: This class handles the ajax cart.
 * Usage: see docs!
 ******************/


var dnCart = new Class({
	Implements: [Options, Events],
	
	options: {
		cartfile: 'example.php',								// this needs to be set to the local cart php
		nothing_in_cart: 'You have no products in your cart',	// modify to local language
		min_reached: 'To remove an item please click the X.',	// modify to local language
		max_reached: 'You have reached the maximum number for this item.',	// modify to local language
		message_delay: 5000,									// milliseconds while message is shown
		init_json: ''											// initial json data to process on cart creation
	},


	//////////////////////////////////////////////////////////////////////////////
	// constructor
		initialize: function(options){
			// set default options
				this.setOptions(options);
			// init cart with json (if specified)
				if(this.options.init_json.length > 0) this.update_cart(JSON.decode(this.options.init_json));
		},
	
	//////////////////////////////////////////////////////////////////////////////
	// Set items in cart
		set_item: function(id, number, min, max){
			// minimum is 1 by default, max is 50
				if(!$defined(min)) min = 1;
				if(!$defined(min)) min = 50;
			// check to see if this product is even in the cart, if not add_line
				if(!$chk($(id))) return this.add_line(id, number);
			// make sure it is an integer, if not set to min
				number = number.toInt();
				if(isNaN(number)) number = min;
			// check min and max
				if(number > max){
					number = max;
					this.show_message(this.options.max_reached);
				}
				if(number < min){
					number = min;
					this.show_message(this.options.min_reached);
				}
			// now set the quantity element to the new number
				$('quantity['+id+']').value = number;
			// finally, save the cart
				this.save_cart();
			return true;
		},
		add_line: function(id, number){
			// add line requires a refresh (this is the product row <tr> will be generated)
				window.location=this.options.cartfile+'?setproduct='+id+'&quantity='+number;
			return true;
		},
	//////////////////////////////////////////////////////////////////////////////
	// Add items to the cart
		add_one: function(id){
			// add one
				return this.add_number(id, 1);
		},
		add_number: function(id, number){
			// get quantity values
				var qelement = $('quantity['+id+']');
				var value = qelement.value.toInt();
			// set item
				return this.set_item(id, value+number);
		},

	//////////////////////////////////////////////////////////////////////////////
	// Remove items from cart	
		remove_one: function(id){
			// remove one
				return this.remove_number(id, 1);
		},
		remove_number: function(id, number){
			// get quantity values
				var qelement = $('quantity['+id+']');
				var value = qelement.value.toInt();
			// set item
				return this.set_item(id, value-number);
		},
		remove_line: function(id){
			// hide the entire line
				$(id).hide();
			// remove this item from the cart
				var r = new Request.JSON({ 'url' : this.options.cartfile, 'method':'get','data': 'removeproduct='+id, link: 'chain' });
				var self = this;
				r.addEvent('success',function(){window.location=self.options.cartfile;});				
				r.send();
			// now destroy and save
				//$(id).destroy();
				//return this.save_cart();
		},

	//////////////////////////////////////////////////////////////////////////////
	// Handle various requests (saves, refresh, etc.)
		save_cart: function(){
			var qstring = 'json=yes&setproducts=now';
			//var pcnt = 0;
			// create query string
				$('cartbox').getElements('div.oneproduct').each(function(el){
					// if the quantity field exists
						if($chk($('quantity['+el.id+']'))){
							// get the quantity value
								var v = $('quantity['+el.id+']').value.toInt();
							// if non-numeric, fix
								if(isNaN(v)) v = $('quantity['+el.id+']').value = 1;
							// now add to qstring
								qstring += '&quantity['+el.id+']='+v;
							// counter
								//pcnt++;
						}
					// if the these fields exists, add to qstring
						if($chk($('country'))) qstring += '&country='+$('country').value;
						if($chk($('paymethod'))) qstring += '&paymethod='+$('paymethod').value;
						if($chk($('promocode'))) qstring += '&promocode='+$('promocode').value;
				});
			// no products! empty the cart!
				//if(pcnt == 0) qstring = 'json=yes&emptycart=now';
			// send a request to me
				var r = new Request.JSON({ 'url' : this.options.cartfile, 'method':'get','data': qstring, link: 'chain' });
				var self = this;
				r.addEvent('success',function(data){self.update_cart(data)});
				r.send();
			return true;
		},
		// refreshes without changing anything about the cart
		refresh_cart: function(){
				var qstring = 'json=yes&';
			// send a request to me
				var r = new Request.JSON({ 'url' : this.options.cartfile, 'method':'get','data': qstring, link: 'chain' });
				var self = this;
				r.addEvent('success',function(data){self.update_cart(data)});
				r.send();
			return true;
		
		},
		// updates the divs
		update_cart: function(data){
			// go through each product
				var pcnt = 0;
				var self = this;	// this is only needed for calling self from within functions
				if($defined(data.products)){
					// list the product details
						var products = new Hash(data.products);
						products.each(function(item, id){
							// does this product currently exist in the list?
								if(!$chk($(id))) return self.refresh_page();
							// it does, so list its parameters
								if($chk($('price['+id+']'))) $('price['+id+']').set('html',item.price);
								if($chk($('fullprice['+id+']'))) $('fullprice['+id+']').set('html',item.fullprice);			
								if($chk($('quantity['+id+']'))) $('quantity['+id+']').value = item.quantity;
							pcnt++;
						});
				}
			// if no products left and error div exists
				if(pcnt == 0) this.show_message(this.options.nothing_in_cart);

			// go through each product to see if there are any which have been removed
				$$('.oneproduct').each(function(el){
					// if this product does not exist, remove the line
						if(!products.has(el.id)) self.remove_line(el.id);
				});


			// go through each discount
				// reset the discount
					$('discountlist').set('html','');
				// run through all of them				
					if($defined(data.discounts)){
						var discounts = new Hash(data.discounts);
						discounts.each(function(item, id){
							// show the discount if needed
							if(item.show == true){
								var el = new Element('div', { 'class':'discountbox' });
								el.set('html',item.name+"<strong>"+item.price_str+"</strong>");
								el.inject($('discountlist'));
							}
							// show the note if needed
							if(item.note != ''){
								self.show_message(item.note);
							}
						});
					}
			// discount code valid? set icon!
				this.set_promo_code_result(data.discount_code_valid);
			// set global stuff
				if($chk($('discount'))) $('discount').set('html',data.discount);
				$('shipping').set('html',data.shipping);
				$('total').set('html',data.total);
			// set note
				if($defined(data.note)) this.show_message(data.note);
			// set local currency (hide if none returned)
				if($chk($('localtotal'))){
					if($defined(data.localtotal)){
						$('localtotal').set('html',data.localtotal);
						$('localtotaldiv').reveal();
					}
					else{
						$('localtotal').set('html','--');
						$('localtotaldiv').dissolve();
					}
				}
			// set euro currency (hide if none returned)
				if($chk($('eurototal'))){
					if($defined(data.eurototal)){
						$('eurototal').set('html',data.eurototal);
						$('eurototaldiv').reveal();
					}
					else{
						$('eurototal').set('html','--');
						$('eurototaldiv').dissolve();
					}
				}
			return true;
		},
		refresh_page: function(){
			window.location = this.options.cartfile;
			return true;
		},

	//////////////////////////////////////////////////////////////////////////////
	// Promocode stuff
		check_promo_code: function(){
			// remove success/fail
				$('promocheck').removeClass('okay');
				//$('promocheck').removeClass('error');
			// add progress
				$('promocheck').addClass('progress');
			// check this promo code
				return this.save_cart();
		},
		set_promo_code_result: function(result){
			// just return if promocheck not valid
				if(!$chk($('promocheck'))) return false;
			// turn off progress
				$('promocheck').removeClass('progress');
				$('promocheck').removeClass('okay');
			// was a promo code not even entered?
				if($('promocode').value == '') return false;
			// success or failure?
				if(result){
					$('promocheck').addClass('okay');
					$('promocheck').removeClass('error');
				}
				else  $('promocheck').addClass('error');
			return true;
		},
	//////////////////////////////////////////////////////////////////////////////
	// Show a message
		show_message: function(message){
			// todo: clear delay timer here!
			// no message is not displayed!
				if(message == '') return false;
			// if div exists, show it for 2 seconds
				if($chk($('cartmessage'))){
					$('cartmessage').set('html',message);
					$('cartmessage').reveal();
					(function(){
						$('cartmessage').dissolve();
					}).delay(this.options.message_delay);
				}
			// no div, so display alert
				else alert(message);
			return true;
		}
			
	});