var HomeRotator = new Class({
	totalimages: null,
	currentimage: null,
	images: null,
	
	initialize: function(path) {
		this.images = $$(path);
		
		this.totalimages = this.images.length;
		this.currentimage = 0;

		//	Set initial state
		if ( this.totalimages >= 1) {
			this.images.each(function(image, index) {
				if (index == this.currentimage) {
					image.setStyle('opacity', '1');
				} else {
					image.setStyle('opacity', '0');
				}
			}.bind(this));
	
			setInterval(this.rotateImage.bind(this), 5000);
		}
	},
	
	rotateImage: function () {
		nextimage = this.currentimage + 1;

		if (nextimage == this.totalimages) {
			nextimage = 0;
		}

		var myElementsEffects = new Fx.Elements([this.images[this.currentimage],this.images[nextimage]], {duration:1500});
		myElementsEffects.start({
		    '0': { 'opacity': [1, 0]},
		    '1': { 'opacity': [0, 1]}
		});

		this.currentimage = this.currentimage + 1;
		
		if (this.currentimage == this.totalimages) {
			this.currentimage = 0;
		}
	}
});

	var ScrollBar = new Class({

		Implements: [Events, Options],

		options: {
			maxThumbSize: 15,
			wheel: 8,
			arrows: true,
			hScroll: true // horizontal scrollbars
		},

		initialize: function(main, content, options){
			this.setOptions(options);
			
			this.main = $(main);
			this.content = $(content);
			
			if (this.options.arrows == true){
				this.arrowOffset = 30;
			} else {
				this.arrowOffset = 0;
			}
			
			if (this.options.hScroll == true){
				this.hScrollOffset = 15;
			} else {
				this.hScrollOffset = 0;
			}				

			this.vScrollbar = new Element('div', {
    				'class': 'vScrollbar'
				}).injectAfter(this.content);				

			if (this.options.arrows == true){				
				this.arrowUp = new Element('div', {
    					'class': 'arrowUp'
					}).injectInside(this.vScrollbar);
			}	

			this.vTrack = new Element('div', {
    				'class': 'vTrack'
				}).injectInside(this.vScrollbar);
				
			this.vThumb = new Element('div', {
    				'class': 'vThumb'
				}).injectInside(this.vTrack);

			if (this.options.arrows == true){				
				this.arrowDown = new Element('div', {
    					'class': 'arrowDown'
					}).injectInside(this.vScrollbar);
			}		
			
			this.hScrollbar = new Element('div', {
    				'class': 'hScrollbar'
				}).injectAfter(this.vScrollbar);

			if (this.options.arrows == true){
				this.arrowLeft = new Element('div', {
    					'class': 'arrowLeft'
					}).injectInside(this.hScrollbar);
			}		

			this.hTrack = new Element('div', {
    				'class': 'hTrack'
				}).injectInside(this.hScrollbar);
				
			this.hThumb = new Element('div', {
    				'class': 'hThumb'
				}).injectInside(this.hTrack);							
	
			if (this.options.arrows == true){
				this.arrowRight = new Element('div', {
    					'class': 'arrowRight'
					}).injectInside(this.hScrollbar);
			}											

			this.corner = new Element('div', {
    				'class': 'corner'
				}).injectAfter(this.hScrollbar);
			
			this.bound = {
				'vStart': this.vStart.bind(this),
				'hStart': this.hStart.bind(this),				
				'end': this.end.bind(this),
				'vDrag': this.vDrag.bind(this),
				'hDrag': this.hDrag.bind(this),				
				'wheel': this.wheel.bind(this),
				'vPage': this.vPage.bind(this),
				'hPage': this.hPage.bind(this)				
			};

			this.vPosition = {};
			this.hPosition = {};			
			this.vMouse = {};
			this.hMouse = {};			
			this.update();
			this.attach();
		},

		update: function(){

			this.main.setStyle('height', this.content.offsetHeight + this.hScrollOffset);
			this.vTrack.setStyle('height', this.content.offsetHeight - this.arrowOffset);
						
			this.main.setStyle('width', this.content.offsetWidth + 15);
			this.hTrack.setStyle('width', this.content.offsetWidth - this.arrowOffset);

			// Remove and replace vertical scrollbar			
			if (this.content.scrollHeight <= this.main.offsetHeight) {
				this.vScrollbar.setStyle('display', 'none');
				if (this.options.hScroll == true){				
					this.hTrack.setStyle('width', this.hTrack.offsetWidth + 15);
				}	
				this.content.setStyle('width', this.content.offsetWidth + 15);	
			} else {
				this.vScrollbar.setStyle('display', 'block');			
			}
			
			if (this.options.hScroll == true){			
			
				// Remove and replace horizontal scrollbar
				if (this.content.scrollWidth <= this.main.offsetWidth) {
					this.hScrollbar.setStyle('display', 'none');
					this.vTrack.setStyle('height', this.vTrack.offsetHeight + this.hScrollOffset);				
					this.content.setStyle('height', this.content.offsetHeight + this.hScrollOffset);	
				} else {
					this.hScrollbar.setStyle('display', 'block');			
				}
			
				// Remove and replace bottom right corner spacer			
				if (this.content.scrollHeight <= this.main.offsetHeight || this.content.scrollWidth <= this.main.offsetWidth) {
					this.corner.setStyle('display', 'none');				
				} else {
					this.corner.setStyle('display', 'block');			
				}		
			
				// Horizontal

				this.hContentSize = this.content.offsetWidth;
				this.hContentScrollSize = this.content.scrollWidth;
				this.hTrackSize = this.hTrack.offsetWidth;

				this.hContentRatio = this.hContentSize / this.hContentScrollSize;

				this.hThumbSize = (this.hTrackSize * this.hContentRatio).limit(this.options.maxThumbSize, this.hTrackSize);

				this.hScrollRatio = this.hContentScrollSize / this.hTrackSize;

				this.hThumb.setStyle('width', this.hThumbSize);

				this.hUpdateThumbFromContentScroll();
				this.hUpdateContentFromThumbPosition();			

			} else {
					this.hScrollbar.setStyle('display', 'none');
					this.corner.setStyle('display', 'none');										
			}
			

			// Vertical
			
			this.vContentSize = this.content.offsetHeight;
			this.vContentScrollSize = this.content.scrollHeight;
			this.vTrackSize = this.vTrack.offsetHeight;

			this.vContentRatio = this.vContentSize / this.vContentScrollSize;

			this.vThumbSize = (this.vTrackSize * this.vContentRatio).limit(this.options.maxThumbSize, this.vTrackSize);

			this.vScrollRatio = this.vContentScrollSize / this.vTrackSize;

			this.vThumb.setStyle('height', this.vThumbSize);

			this.vUpdateThumbFromContentScroll();
			this.vUpdateContentFromThumbPosition();
			
		},

		vUpdateContentFromThumbPosition: function(){
			this.content.scrollTop = this.vPosition.now * this.vScrollRatio;
		},
		
		hUpdateContentFromThumbPosition: function(){
			this.content.scrollLeft = this.hPosition.now * this.hScrollRatio;
		},		

		vUpdateThumbFromContentScroll: function(){
			this.vPosition.now = (this.content.scrollTop / this.vScrollRatio).limit(0, (this.vTrackSize - this.vThumbSize));
			this.vThumb.setStyle('top', this.vPosition.now);
		},
		
		hUpdateThumbFromContentScroll: function(){
			this.hPosition.now = (this.content.scrollLeft / this.hScrollRatio).limit(0, (this.hTrackSize - this.hThumbSize));
			this.hThumb.setStyle('left', this.hPosition.now);
		},		

		attach: function(){
			var browser = this.detect();
			this.vThumb.addEvent('mousedown', this.bound.vStart);
			if (this.options.wheel) {
				if (browser[1] == 'firefox' && browser[2].match(/^4/)) {
					this.content.addEvent('DOMMouseScroll', this.bound.wheel);
				} else {
					this.content.addEvent('mousewheel', this.bound.wheel);
				}
			}
			this.vTrack.addEvent('mouseup', this.bound.vPage);
			
			this.hThumb.addEvent('mousedown', this.bound.hStart);
			this.hTrack.addEvent('mouseup', this.bound.hPage);			
			
			if (this.options.arrows == true){
				this.arrowUp.addEvent('mousedown', function(event){
						this.interval = (function(event){
						this.content.scrollTop -= this.options.wheel;
						this.vUpdateThumbFromContentScroll();
					}.bind(this).periodical(40))
				}.bind(this));
			
				this.arrowUp.addEvent('mouseup', function(event){
					$clear(this.interval);
				}.bind(this));
			
				this.arrowUp.addEvent('mouseout', function(event){
					$clear(this.interval);
				}.bind(this));
						
				this.arrowDown.addEvent('mousedown', function(event){
						this.interval = (function(event){
						this.content.scrollTop += this.options.wheel;
						this.vUpdateThumbFromContentScroll();
					}.bind(this).periodical(40))
				}.bind(this));
			
				this.arrowDown.addEvent('mouseup', function(event){
					$clear(this.interval);
				}.bind(this));
			
				this.arrowDown.addEvent('mouseout', function(event){
					$clear(this.interval);
				}.bind(this));
			
				this.arrowLeft.addEvent('mousedown', function(event){
						this.interval = (function(event){
						this.content.scrollLeft -= this.options.wheel;
						this.hUpdateThumbFromContentScroll();
					}.bind(this).periodical(40))
				}.bind(this));
			
				this.arrowLeft.addEvent('mouseup', function(event){
					$clear(this.interval);
				}.bind(this));
			
				this.arrowLeft.addEvent('mouseout', function(event){
					$clear(this.interval);
				}.bind(this));
			
				this.arrowRight.addEvent('mousedown', function(event){
						this.interval = (function(event){
						this.content.scrollLeft += this.options.wheel;
						this.hUpdateThumbFromContentScroll();
					}.bind(this).periodical(40))
				}.bind(this));
			
				this.arrowRight.addEvent('mouseup', function(event){
					$clear(this.interval);
				}.bind(this));
			
				this.arrowRight.addEvent('mouseout', function(event){
					$clear(this.interval);
				}.bind(this));
			}			
						
		},
		
		wheel: function(event){
			this.content.scrollTop -= event.wheel * this.options.wheel;
			this.vUpdateThumbFromContentScroll();
			event.stop();
		},

		vPage: function(event){
			if (event.page.y > this.vThumb.getPosition().y) this.content.scrollTop += this.content.offsetHeight;
			else this.content.scrollTop -= this.content.offsetHeight;
			this.vUpdateThumbFromContentScroll();
			event.stop();
		},
		
		hPage: function(event){
			if (event.page.x > this.hThumb.getPosition().x) this.content.scrollLeft += this.content.offsetWidth;
			else this.content.scrollLeft -= this.content.offsetWidth;
			this.hUpdateThumbFromContentScroll();
			event.stop();
		},		

		vStart: function(event){
			this.vMouse.start = event.page.y;
			this.vPosition.start = this.vThumb.getStyle('top').toInt();
			document.addEvent('mousemove', this.bound.vDrag);
			document.addEvent('mouseup', this.bound.end);
			this.vThumb.addEvent('mouseup', this.bound.end);
			event.stop();
		},
		
		hStart: function(event){
			this.hMouse.start = event.page.x;		
			this.hPosition.start = this.hThumb.getStyle('left').toInt();
			document.addEvent('mousemove', this.bound.hDrag);
			document.addEvent('mouseup', this.bound.end);
			this.hThumb.addEvent('mouseup', this.bound.end);
			event.stop();
		},		

		end: function(event){
			document.removeEvent('mousemove', this.bound.vDrag);
			document.removeEvent('mousemove', this.bound.hDrag);			
			document.removeEvent('mouseup', this.bound.end);
			this.vThumb.removeEvent('mouseup', this.bound.end);
			this.hThumb.removeEvent('mouseup', this.bound.end);			
			event.stop();
		},

		vDrag: function(event){
			this.vMouse.now = event.page.y;
			this.vPosition.now = (this.vPosition.start + (this.vMouse.now - this.vMouse.start)).limit(0, (this.vTrackSize - this.vThumbSize));
			this.vUpdateContentFromThumbPosition();
			this.vUpdateThumbFromContentScroll();
			event.stop();
		},
		
		hDrag: function(event){
			this.hMouse.now = event.page.x;
			this.hPosition.now = (this.hPosition.start + (this.hMouse.now - this.hMouse.start)).limit(0, (this.hTrackSize - this.hThumbSize));
			this.hUpdateContentFromThumbPosition();
			this.hUpdateThumbFromContentScroll();
			event.stop();
		},
		
		detect: function() {
			var ua = navigator.userAgent.toLowerCase(),
			platform = navigator.platform.toLowerCase(),
			UA = ua.match(/(opera|ie|firefox|chrome|version)[\s\/:]([\w\d\.]+)?.*?(safari|version[\s\/:]([\w\d\.]+)|$)/) || [null, 'unknown', 0],
			mode = UA[1] == 'ie' && document.documentMode;
			return UA;
		}

	});

//	Made the menu a bit more userfriendly: on leave the menu stays selected for a few extra seconds
window.addEvent('domready', function() {
	if ($('nav')) {
		var timeoutID;
	
		$('nav').addEvent('mouseover', function(event) {
			$clear(timeoutID);
		
			parentMenuItem = $(event.target).getParent('li.level0');

			if (!parentMenuItem) {
				return;
			}

			$$('#nav li.over').each(function(item) {
				if (item != parentMenuItem) {
					item.removeClass('over');

					// 	IE6
					if (Browser.Engine.trident && Browser.Engine.version < 5) {
						var uL = item.getChildren('ul')[0];
						uL.removeClass('shown-sub');
					}
				}
			});
			parentMenuItem.addClass('over');

			// 	IE6
			if (Browser.Engine.trident && Browser.Engine.version < 5) {
				var uLs = parentMenuItem.getChildren('ul');
				uLs.each(function(uL) {
					uL.addClass('shown-sub');
				});
			}
		});
		$('nav').addEvent('mouseleave', function(event) {
			timeoutID = unselectMenu.delay(5000);
		});
	}
});

unselectMenu = function() {
	$$('#nav li.over').each(function(item) {
		item.removeClass('over');
		
		if (Browser.Engine.trident && Browser.Engine.version < 5) {
			var uLs = item.getChildren('ul');
			uLs.each(function(uL) {
				uL.removeClass('shown-sub');
			});
		}		
	});
};

setLocation = function(url) {
	window.location.href = url;
};

updateCustomerData = function(responseTree, responseElements, responseHTML, responseJavaScript) {
	if (responseHTML) {
		// Fix Javascript
		//responseHTML = responseHTML.replace("Element.addClassName(this,'over')", "$(this).addClass('over')");
		//responseHTML = responseHTML.replace("Element.removeClassName(this,'over')", "$(this).removeClass('over')");
	
		var dummy = new Element('div');
		dummy.set('html', responseHTML);
		
		var divs = dummy.getChildren();

		if (divs.length == 2) {
			if($('customer_data_placeholder')){
				divs[0].replaces($('customer_data_placeholder'));
				divs[1].inject($('wishlist'), 'after');
			}
		} else if (divs.length == 3) {
			if($('customer_data_placeholder')){
				divs[0].replaces($('customer_data_placeholder'));
				divs[1].inject($('wishlist'), 'after');
				
				//	Welcome message
				var metanav = $$('.metanav')[0];
				divs[2].inject(metanav, 'bottom');
				//divs[2].inject($('pocket'), 'after');
			}
		}
		
		/**
		 * Event handling for pocket
		 */
		$('pocket').addEvent('mouseenter', pocketOpen);
		$('pocket').addEvent('mouseleave', pocketClose);
		
		//	Check if pocket is open too long
		//	TODO Check mouse position
		pocketCheckId = pocketCheck.periodical(5000, window);
	}	
};
//	TODO Move to class, rewrite for Prototype for Magento part of the site
//	Should we use periodical? We only check once
var pocketOpen = false;
var pocketCheckId = null;
var pocketCheck = function() {
	if (pocketOpen) {
		pocketClose();
	}
};
var pocketClose = function() {
	$('pocket').removeClass('over');
	pocketOpen = false;
	if (pocketCheckId) {
		pocketCheckId = $clear(pocketCheckId);
	}
};
var pocketOpen = function() {
	$('pocket').addClass('over');
	pocketOpen = true;
	pocketCheckId = pocketCheck.periodical(5000, window);
};

if (!$chk(storecode)) {
	var storecode = 'default';
}
window.addEvent('domready', function(storecode) {
	//	Will only work if both the shop and EOS site are on the same domain
	if ($('customer_data_placeholder')) {
		var request = new Request.HTML({
			method: 'get',
			url: '/shop/' + storecode + '/custom/customer/',
			onSuccess:	updateCustomerData,
			onFailure:	updateCustomerData
		}).send();
	
		/*var postObject = JSON.encode({
			action:	'EosSimpleParserWrapper',
			templatePath:	'includes/shop/customer_data.tpl'});
	
		var request = new Request.JSON({
			url:	'/sbeos/ajax/JsonCall.php',
			data:	{json: postObject},
			onComplete:	updateCustomerData
		}).send();*/
	}
}.pass([storecode]));

window.addEvent('load', function(){
	var searchInput = $('search');

	$$('#search_mini_form .form-button').each(function(item) {
		item.addEvent('click', function() {
			if(searchInput.get('value') != searchInput.defaultValue) {
				$('search_mini_form').submit();
			}
			return false;
		});
	});
	
	if ($chk(searchInput)) {
		searchInput.addEvent('focus', function() {
			if(searchInput.get('value') == searchInput.defaultValue) {
				searchInput.set('value', '');
			}
		});
		searchInput.addEvent('blur', function() {
			if(searchInput.get('value') == '') {
				searchInput.set('value', searchInput.defaultValue);
			}
		});
	}
	
	var formMessage = $('confirmation_text');
	if ($chk(formMessage)) {
		$('block_content').setStyle('display', 'none');
	
		var messageText = formMessage.innerHTML;
		
		var newMessageUL = new Element('ul', {'class': 'messages'});
		newMessageUL.set('html', '<li class="success-msg"><ul><li>' + messageText + '</li></ul></li>');
		
		var container = $$('.middle-container');
		container = container[0];
		newMessageUL.inject($(container), 'top');
	}
});

window.addEvent('domready', function() {
	// var mySlide<sbeos:print value="${content:id}"/> = new Fx.Slide('div<sbeos:print value="${content:id}"/>').hide();
	$$('.faqItem').each(function(elem) {
		var parent = elem;
		var ans = elem.getElements('.answer').pop();
		var question = elem.getElements('.question').pop();
		var mySlide = new Fx.Slide(ans).hide();
		
		question.addEvent('click', function() {
			parent.toggleClass('questionOpen');
			mySlide.toggle();
		});
	});
	
	// Hide empty elements on content pages
	if ($('block_intro')) {
		innerHtml = $('block_intro').get('html').trim();
		if (innerHtml == '' || innerHtml == '<br>') {
			$('block_intro').setStyle('display', 'none');
		}
	}

	if ($('block_title')) {
		innerHtml = $('block_title').get('html').trim();
		if (innerHtml == '' || innerHtml == '<br>') {
			$('block_title').setStyle('display', 'none');
		}
	}

	//	Custom ESAM image editing events
	if ($('background_image')) {
		$('background_image').addEvent('complete', function() {
			//	Strip resize info
			var imgSrc = 'url(' + $('background_image').getProperty('src') + ')';
			imgSrc = imgSrc.substring(0, imgSrc.indexOf('&actions'));
			$('background_image_container').setStyle('background-image', imgSrc);	
		});
	}
	if ($('bg_right_image')) {
		$('bg_right_image').addEvent('complete', function() {
			//	Strip resize info
			var imgSrc = 'url(' + $('bg_right_image').getProperty('src') + ')';
			imgSrc = imgSrc.substring(0, imgSrc.indexOf('&actions'));
			$('bg_right_image_container').setStyle('background-image', imgSrc);	
		});
	}
	if ($('bg_left_image')) {
		$('bg_left_image').addEvent('complete', function() {
			//	Strip resize info
			var imgSrc = 'url(' + $('bg_left_image').getProperty('src') + ')';
			imgSrc = imgSrc.substring(0, imgSrc.indexOf('&actions'));
			$('bg_left_image_container').setStyle('background-image', imgSrc);	
		});
	}	
});

