window.addEvent('domready', function() {
	// get current active accordion element
	var accordionElements = $$('#accordion .toggler').get('class');
	var activeElement = accordionElements.indexOf('toggler active');
	//create Accordion instance for side navigation (products/ yogi tea story)
	// if($chk('.yogiTeaCategoryNav')){
	// 	console.log('yoginav found');
	// }else{
	// 	console.log('not');
	// }
	if( $$('.yogiTeaCategoryNav').length!=0 || $$('.productsCategoryNav').length != 0){
		var myAccordion = new Accordion($('accordion'), 'li.toggler span', 'ul.element', {
			opacity: false,
		  	display: activeElement,
		    alwaysHide: false,
			initialDisplayFx: true,
		    onActive: function(toggler) { toggler.setStyle('background-position', 'top'); }, 
		    onBackground: function(toggler) { toggler.setStyle('background-position', 'bottom'); }
		});		
		
	}
	
	var myFaqAccordion = new Accordion($('faqContainer'), '#faqContainer dt', '#faqContainer dd', {
		opacity: false,
	  	display: -1,
	    alwaysHide: true,
	    onActive: function(toggler) { toggler.setStyle('background-position', 'top'); }, 
	    onBackground: function(toggler) { toggler.setStyle('background-position', 'bottom'); }

	});
	
	function fadeThis (el, direction) {
		if (direction == 'in') {
			if (!Browser.Engine.trident) {
				el.fade('in');
			}else{
				el.fade('show');
			}
		}else{
			if (!Browser.Engine.trident) {
				el.fade('out');
			}else{
				el.fade('hide');
			}
		}	
	}
	String.implement({

	    capitalizeFirst: function(){
	       var chars = this.split('');
	       if (!chars.length) return this;
	       chars.unshift(chars.shift().capitalize());
	       return chars.join('');
	    }

	});

	
	
	$('langSelect').fade('hide');
	if($chk($('login'))) {
		$('login').fade('hide');
	}


	
	
	$$('#secondaryNav li')[2].addEvents({
		'mouseover': function(){
			fadeThis($('langSelect'), 'in');
		},
		'mouseout': function(){
			fadeThis($('langSelect'), 'out');
		}
	})
	if($chk($('login'))) {
		$$('#secondaryNav li')[0].addEvents({
			'mouseover': function(){
				fadeThis($('login'),'in');
			},
			'mouseout': function(){
				fadeThis($('login'),'out');

			}
		})
	}	
    
	// if this is the product detail page, ingredients and 
	// instructions will appear and disappear
	if ($chk($('instructions')) ) {
		$('ingredientsList').fade('hide');
		$('instructionsText').fade('hide');
		
		$('instructions').addEvent('mouseover', function (){
			fadeThis($('ingredientsList'),'out');
			fadeThis($('instructionsText'),'in');
		})
		$('ingredients').addEvent('mouseover', function (){
			fadeThis($('ingredientsList'),'in');
			fadeThis($('instructionsText'),'out');
		})
	
		$$('.productInfo>p, #packShot, #otherProducts').addEvent('mouseover', function (){
			fadeThis($('ingredientsList'),'out');
			fadeThis($('instructionsText'),'out');
		})
	};
	
	// manipulating the dom to add accordionHeader
	var accordionHeader = new Element('li',{
		'id':'accordionHeader'
	})
	
	$$('.yogiTeaCategoryNav').each(function(el){
		accordionHeader.inject(el, 'top');
	})
	
	//removing the anchor event and triggers the accordion instead
	$$('.yogiTeaCategoryNav .toggler>a').each(function (el) {
		el.getNext('ul').setStyle('display', 'none');
	})	

	$$('.yogiTeaCategoryNav .toggler>a.open').each(function (el) {
		el.getNext('ul').setStyle('display', 'block');
		el.getParent().addClass('active');
	})	
	
	
	
	// if current page is teafinder page, hide and show moods/flavours
	if ($chk($('teafinder')) ) {
		$('flavoursList').fade('hide');
		$('moodsList').fade('hide');
		
		$('moods').addEvent('mouseover', function (){
			fadeThis($('flavoursList'),'out');
			fadeThis($('moodsList'),'in');
		})
		$('flavours').addEvent('mouseover', function (){
			fadeThis($('flavoursList'),'in');
			fadeThis($('moodsList'),'out');
		})
	
		$('content').addEvent('mouseover', function(event){
			fadeThis($('flavoursList'),'out');
			fadeThis($('moodsList'),'out');
		})
		$('descriptionContainer').addEvent('mouseover', function(event){
			fadeThis($('flavoursList'),'out');
			fadeThis($('moodsList'),'out');
		})
		$$('#moodsList li').each(function(el)
		{
			el.addEvent('click', function()
			{
				fadeThis($('flavoursList'),'out');
				fadeThis($('moodsList'),'out');
				
				$$('#teafinder li').each(function(element){element.removeClass('active')});
				el.addClass('active');
				requestProducts.send(
					{
						url: 	'index.php/products/productDataByMood/'+el.get('rel')+'/'+$('lang').get('content'), 
						method: 'post',
						data: 	'value'
					});
			});
		});
		
		$$('#flavoursList li').each(function(el)
		{
			el.addEvent('click', function()
			{
				fadeThis($('flavoursList'),'out');
				fadeThis($('moodsList'),'out');
				
				$$('#teafinder li').each(function(element){element.removeClass('active')});
				el.addClass('active');
				requestProducts.send(
					{
						url: 	'index.php/products/productDataByFlavour/'+el.get('rel')+'/'+$('lang').get('content'), 
						method: 'post',
						data: 	'value'
					});
			});
		});
	};

    if ($chk($('wrapper'))) {
		$('product_'+$('packShot').get('class')).destroy();
		var merry = new MerryGoRound($('wrapper'),{
			wrapper_width : 364,
			wrapper_height : 140,
			wrapper_tag: 'ul',
			cycle         : true,
		    page_controls : true,
		    selector      : 'li',
			previous_button_options : {
		    	'html':'',
		      	'styles' : {
					'cursor'   : 'pointer'
		      	}
			},
			next_button_options : {
			    'html':'',
			  	'styles' : {
					'cursor'   : 'pointer'
		      	}
			}
			
		});
    };
	if ($chk($('heroes'))) {
			$$('.otherProducts').fade('hide');
			$$('#heroes>li').each(function(el)
				{
				el.addEvent('mouseover', function()
					{
						el.getChildren('.otherProducts').position({
							relativeTo: el,
							position: 'upperLeft',
						    // edge: 'upperRight',
							offset:{x: 0, y:200} 
						});
						el.getChildren('.otherProducts').setStyle('z-index',2000);
						el.setStyle('z-index',1000);
						fadeThis(el.getChildren('.otherProducts'),'in');
					}
				);
				el.addEvent('mouseout', function()
					{
						el.getChildren('.otherProducts').setStyle('z-index',10);
						el.setStyle('z-index',0);
						fadeThis(el.getChildren('.otherProducts'),'out');
					}
				);
			});
	}
	
	$$('#downloads li a').each(function (el) {
		el.addEvent('click', function (event){
			event.stop();
			
			if ($chk($('modal'))) {
				$('modal').destroy();
			};
			
				var agreeLink = new Element('a',{
					'id':'agree',
					'text': '',
					'href': el.get('href'),
					events:{
						click: function(e){
							modal.destroy();
						}
					}
				})
				var quitLink = new Element('a',{
					'id':'quit',
					'text': '',
					'href': '#',
					events:{
						click: function(e){
							e.stop();
							modal.destroy();
						}
					}
				});
				var buttons = new Element('div',{
					'id':'buttons'
				});
				var modal = new Element('div', {
					'class': 'mui-box',
					'id':'modal'
				})
				agreeLink.inject(buttons);
				quitLink.inject(buttons);
				
				$('terms').clone().removeClass('hidden').set('id','terms').inject(modal);
				

				new Element('p', {
					'text': $('confirmTerms').get('text')
				}).inject(modal);
				
				buttons.inject(modal);
				modal.inject($('contentWrapper'));
				modal.position();
		})
	}); 
	
	$extend(XML, {
	    hashToHtmlTree: function(hash) {
	        var tree = [];
	        for (var i = 0, l = hash.length; i < l; ++i) {
	            tree[i] = XML.hashToHtmlElement(hash[i]);
	        }
	        return tree;
	    },
	    hashToHtmlElement: function(hash, tag) {
	        var element;
	        if (hash.text) {
	            element = document.newTextNode(hash.text);
	        } else {
	            if (typeof tag === 'undefined') {
	                switch (hash.tag) {
	                    default:
	                        tag = 'div';
	                }
	            }
	            element = document.newElement(tag, hash.attributes)
	                .addClass(hash.tag)
	                .adopt(XML.hashToHtmlTree(hash.children));
	        }
	        return element;
	    }
	});


	
	var requestProducts = new Request(
	{ 
		onRequest: function() {
			$('productContainer').empty();	
			$$('body').removeClass('index');
		},
	    onSuccess: function(response, responseXML) {
	        var gRoots = XML.rootToHashes(responseXML),
	            gTree = XML.hashToHtmlElement(gRoots[0]);
			$(gTree).getElements('div.packshotsmall').each(function  (el) {
				var productBox = new Element('div',{
					'class': 'productSmall'
				});
				var productLink = new Element('a',{
					'href': el.getParent().get('clickPath').trim()
				})
				var productShot = new Element('img',{
					'src' : el.get('text').clean()
				}).inject('productContainer');

				var productName = new Element('span',{
					'text': el.getParent().get('name')
				});
				
				var ingredients = String.split(el.getParent().getElements('div.mainingredients').get('text'), ', ');
			
				var mainIngredientsDE = new Element('span',{
					'class':'mainIngredients',
					'text' : String(el.getParent().getElements('div.mainingredients').get('text')).trim().capitalizeFirst()
				})
				var mainIngredientsEN = new Element('span',{
					'class':'mainIngredients',
					'text' : String(el.getParent().getElements('div.mainingredients').get('text')).trim()
				})
				


				productShot.inject(productLink);
				productName.inject(productLink);

				if ($('lang').get('content')=='de') {
					mainIngredientsDE.inject(productLink);
				}else{
					mainIngredientsEN.inject(productLink);
				}
				
				productLink.inject(productBox);
				productBox.inject($('productContainer'));
				if($chk($('teafinder'))==false) {
					// console.log(el.getParent());
					$$('h2').set('text', el.getParent().getElements('div.categorytitle').get('text'));
					$$('h2').removeClass('sIFR-replaced');
					$('categoryDescription').set('text', el.getParent().getElements('div.categorydesc').get('text'));
					// console.log(el.getParent().getElements('div.categorydesc').get('text'));
					sIFR.replace(h2, {selector: 'h2', css: [ '.sIFR-root {kerning:true;color: '+ $$('h2').getStyle('color') +';}'], wmode: 'transparent'});
				}
			})
		},
		onComplete: function(){ 
			fadeThis($('productContainer'),'in');
		},
		onFailure: function() {
		}
	});

	
	var elProducts = $('nav_categories');
	elProducts.set('slide', {duration: 'long', transition: Fx.Transitions.Pow.easeOut});
	
	var elYogi = $('nav_yogi');
	elYogi.set('slide', {duration: 'long', transition: Fx.Transitions.Pow.easeOut});

	elYogi.slide('hide');
	elProducts.slide('hide');
		
	$('navYogiTea').addEvents({
		'mouseover': function(){
			elYogi.slide('in');
		},
		'mouseout': function(){
			elYogi.slide('out');
		}
	})
	
	$('navProducts').addEvents({
		'mouseover': function(){
			elProducts.slide('in');
		},
		'mouseout': function(){
			elProducts.slide('out');
		}
	})


	$$('#accordion.productsCategoryNav li.toggler span').each(function(el)
	{
		el.addEvent('click', function()
		{
			requestProducts.send(
				{
					url: 	'index.php/products/productData/'+el.get('id').trim()+'/'+$('lang').get('content'), 
					method: 'post'
				});
			
		});
	});
	
	$$('body#de .mainIngredients').each(function(el){
		el.set('text', String(el.get('text')).trim().capitalizeFirst())
	})
	$$('body#de #ingredientsList p').each(function(el){
		el.set('text', String(el.get('text')).trim().capitalizeFirst())
	})
	// =======================
	// = IE HELPER AND FIXES =
	// =======================	

	// fixing the missing :last selector in IE
	$$('#primaryNav>li').getLast().addClass('last');
	$$('#secondaryNav>li').getLast().addClass('last');

	$$('#metaNav>li').getLast().addClass('last-child');
	$$('#metaNav').getFirst().addClass('first-child');
	
	$$('.toggler.active span').each(function  (el) {
		el.setStyle('background-position', 'bottom');
	})
	
});

