

Prototype.Browser = {
	IE:     !!(window.attachEvent && !window.opera),
	Opera:  !!window.opera,
	WebKit: document.childNodes && !document.all && !navigator.taintEnabled,
	Gecko:  (document.getBoxObjectFor != null),
	MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
};

Object.extend(Prototype.Browser, {
     WebKit419: Prototype.Browser.WebKit && (Prototype.BrowserFeatures.XPath),
     WebKit420: Prototype.Browser.WebKit && (!Prototype.BrowserFeatures.XPath),
     IE6:      Prototype.Browser.IE && (typeof window.XMLHttpRequest == "undefined"),
     IE7:      Prototype.Browser.IE && (typeof window.XMLHttpRequest == "object")
});


var SliderBox = Class.create({
	size: 4,
	inaction: false,
	
	slide: function (move, position) {
		if (!this._contentToScroll_prev() && move > 0 ) {
			move = 0;
		} else if (!this._contentToScroll_next() && move < 0) {
			move = 0;
		}

		new Effect.Morph(this.container.down('.slider'), {
			style: 'left: '+(parseInt(this.container.down('.slider').getStyle('left'))+move)+'px',
			duration: 0.5,
			afterFinish: function () {
				this.verticalSlider.setValue(position);
				this.setTriggerVisibility();
				this.inaction = false;
			}.bind(this)
		});

		/*
		new Effect.Move(this.container.select('.slider').first(), {
			x: move,
			y: 0,
			mode: 'relative',
			duration: 0.5,
			transition: Effect.Transitions.sinoidal,
			afterFinish: function () {
				this.setTriggerVisibility();
				this.inaction = false;
			}.bind(this)
		});*/
	},
	
	scrollerSlide: function (value) {
		this.container.select('.slider').first().setStyle({ left: ((value*this.itemWidth)*-1)+'px'});
		this.setTriggerVisibility();
		/*
		if (! this.inaction) {
			//this.inaction = true;
			new Effect.Move(this.container.select('.slider').first(), {
				x: -(value*this.itemWidth),
				y: 0,
				mode: 'absolute',
				duration: 0.1,
				transition: Effect.Transitions.sinoidal,
				afterFinish: function () {
					this.setTriggerVisibility();
					this.inaction = false;
				}.bind(this)
			});
			console.log(-(value*this.itemWidth));
		}*/
	},
	
	_setPosLeft: function(posLeft) {
		this.boxPosLeft = posLeft;
		this.container.select('.slider').first().setStyle({
			left: posLeft + 'px'
		});
	},
	
	_getPosLeft : function () {
		this.boxPosLeft = this.container.select('.slider').first().getStyle('left').replace('px','');
		return this.boxPosLeft; 
	},
	
	_contentToScroll_prev: function (pos) {
		if (! Object.isNumber(pos)) {
			pos = this._getPosLeft();
		}
		
		if (pos >= 0) {
			return false;
		} 
		return true;
	},
	
	_contentToScroll_next: function (pos) {
		if (! Object.isNumber(pos)) {
			pos = this._getPosLeft();
		}
		
		//calculate with of inner items minus width of container
		var width = 0-(this.sliderWidth-this.container.getWidth());
		if ((pos - this.itemWidth) < width) {
			return false;
		}
		return true;
	},
	
	setTriggerVisibility : function () {

		//prev trigger
		if (this._contentToScroll_prev()) {
			this.triggerPrev.up().removeClassName('disabled disabled-prev');
		} else {
			this.triggerPrev.up().addClassName('disabled disabled-prev');
		}
		
		// next trigger
		if (this._contentToScroll_next()) {
			this.triggerNext.up().removeClassName('disabled disabled-next');
		} else {
			this.triggerNext.up().addClassName('disabled disabled-next');
		}
	},
	
	slide_prev: function () {
		if (!this.inaction && !this.triggerPrev.up().hasClassName('disabled')) {
			this.inaction = true;
			var current = parseInt(this.container.down('.slider').getStyle('left'));
			var targetIndex = Math.round(this.verticalSlider.value) - 1;
			if(parseInt(this.verticalSlider.value) != this.verticalSlider.value) {
				targetIndex = Math.floor(this.verticalSlider.value)
			}
			var target = -(this.itemWidth * targetIndex);
			this.slide(target - current, targetIndex);
			if( this.container.select('.slider-count').first() && this.container.select('.slider-count').first().innerHTML != 1) {
				this.sliderCount = this.sliderCount - 1;
				this.container.select('.slider-count').first().update(this.sliderCount);
			}
		}
	},
	
	slide_next: function () {
		if (!this.inaction && !this.triggerNext.up().hasClassName('disabled')) {
			this.inaction = true;
			var current = parseInt(this.container.down('.slider').getStyle('left'));
			var targetIndex = Math.round(this.verticalSlider.value) + 1;
			if(parseInt(this.verticalSlider.value) != this.verticalSlider.value) {
				targetIndex = Math.ceil(this.verticalSlider.value)
			}
			var target = -(this.itemWidth * targetIndex);
			this.slide(target - current, targetIndex);
			if(this.container.select('.slider-count').first() && this.container.select('.slider-count').first().innerHTML != this.container.select('.pages-count').first().innerHTML) {
				this.sliderCount = this.sliderCount + 1;
				this.container.select('.slider-count').first().update(this.sliderCount);
			}
		}
	},
	
	indexOfItem: function (item) {
		if (!item) {
			item = this.container.down('.slider .article.active');
		}
		
		retVal = 0;
		this.items.each(function (curitem, index) {
			if (curitem == item) {
				retVal = index;
			}
		});
		return retVal;
	},
		
	jumpToActiveItem: function () {
		activeElement = this.container.down('.slider .article.active');
		if (!activeElement) {
			activeElement = this.items.first();
		}
		pos = 0 - activeElement.positionedOffset().left;
		while (! this._contentToScroll_next(pos+this.itemWidth)) {
			pos = pos + this.itemWidth;
		}
		this._setPosLeft(pos);
	},
	
	rearrangeArticleContent: function() {
		var articles = this.container.select('.article');
		articles.each(function(item) {
			var link = item.select('.article-image a').first().clone();
			link.childElements().each(function(linkchild) {
				linkchild.remove();
			});
			var contents = new Array();
			item.childElements().each(function(elem) {
				contents.push(elem.remove());
			});
			
			item.insert(link);
			contents.each(function(elem) {
				item.childElements().first().insert(elem);
			});
		});
	},
	
	sizeHandle: function() {
		var handleMaxWidth = parseInt(this.verticalSliderContainer.up().getWidth());
		var sliderWidth = this.container.down('div.slider').childElements().length * parseInt(this.container.down('div.slider').childElements().first().getWidth());
		var sliderWrapperWidth = parseInt(this.container.down('.articles-content').getWidth());
		var handleWidth = sliderWrapperWidth / sliderWidth * handleMaxWidth;
		
		if(handleWidth > handleMaxWidth) {
			handleWidth = handleMaxWidth;
		}
		
		this.verticalSliderContainer.down().setStyle({ width: handleWidth+'px' })
	},
	
	initialize: function(container) {

		try {
			this.sliderCount = 0;
			this.container = container;
			this.items = container.select('.slider .article');
			this.itemWidth = this.items.first().getWidth();
			this.itemCount = this.items.size();
			this.sliderWidth = this.itemWidth*this.itemCount;
			this.currentItem = 0;
	
			this.triggerPrev = container.down('.slider-box-trigger-prev');
			this.triggerPrev.observe('click', this.slide_prev.bind(this));
			
			this.triggerNext = container.down('.slider-box-trigger-next');
			this.triggerNext.observe('click', this.slide_next.bind(this));
	
			this.verticalSliderContainer = container.down('.slider-box-trigger-slider');
			this.sizeHandle();
			
			if (this.itemCount-this.size >= 0) {
				this.jumpToActiveItem();
				
				this.verticalSlider = new Control.Slider(this.verticalSliderContainer.down('.handle'), this.verticalSliderContainer, {
					range: $R(0,this.itemCount-this.size),
					sliderValue: this.indexOfItem(),
					onSlide: this.scrollerSlide.bind(this),
					onChange: this.scrollerSlide.bind(this)
				});
			} else {
				//this.container.down('.articles-navigation').hide();
				this.verticalSliderContainer.up('div').addClassName('slider-box-trigger-slider-deact');
			}
			
			this.setTriggerVisibility();
		} catch (e) {
			if (Object.isFunction(console.log)) {
				console.log(e);
			}
		}
	}
});


var ImageSlide = Class.create({
	
	//currently active item, count from 0
	items: [],
	currentItem: 0,
	navigation: [],
	pe: false,
	inProgress: false,
	autoplay: false,
	
	/**
	 * Initialize class
	 *
	 * @container: html-parent-container, usually with class fce-imageslide
	 */
	initialize: function(container) {
		this.container  = container;
		this.height = 0;
		this.items = this.container.select('ul.images>li');
		this.itemCount = this.items.size();
		
		if(this.container.hasClassName('autoplay')) {
			this.autoplay = true;
		}
		
		this.items.each(function (item, index) {
			imgTag = item.select('img').first();
			//preload all images
			preloadImage = new Image();
			preloadImage.src = imgTag.readAttribute('src');
			
			//search for image with greatest height
			if (Prototype.Browser.IE) {
				regExp = new RegExp(/\<img.*height[^\d]+(\d+)/i);
				match = regExp.exec(item.innerHTML);
				tempHeight = match[1];
			} else {
				tempHeight = imgTag.readAttribute('height');
			}
			this.height = (tempHeight > this.height) ? tempHeight : this.height;
			
			//display first image
			if (index == this.currentItem) {
				item.show();
			}
		}.bind(this));
		//FG, this is a hotfix, please change 
		if (this.container.hasClassName('imageslider')) {
			this.container.setStyle({height: this.height + 'px'});
		}

		if (this.itemCount > 1) {
			this.navigation = this.container.select('ul.navigation>li');
			this.navigation.each(function (item, index) {
				item.observe('click', function(event) {
					elementClicked = event.element().tagName.toLowerCase() == 'li' ? event.element() : event.element().up('li');
					this.currentItem = this.navigation.indexOf(elementClicked);
					if(this.autoplay) {
						this.pe.stop();
					}
					this.showItem(this.currentItem);
				}.bindAsEventListener(this));
			}.bind(this));
			
			//startPeriodicalExecuter
			if(this.autoplay) {
				this.pe = new PeriodicalExecuter(function(pe) {
					this.nextItem();
				}.bind(this), 5);
			}
		}
	},
	
	nextItem: function () {
		this.items[this.currentItem].fade();
		this.currentItem = (this.currentItem + 1) % this.itemCount;
		this.items[this.currentItem].appear();
		
		if (this.navigation.size() > 0) {
			this.navigation.invoke('removeClassName', 'act');
			this.navigation[this.currentItem].addClassName('act');
		}
	},
	
	showItem: function (itemPos) {
		inProgress = false; 
		this.items.each(function (item) {
			if (item.inProgress) {
				inProgress = true;
			}
		});
		
		if (! inProgress) {
			this.items.each(function (item, index) {
				item.inProgress = true;
				if (index == itemPos) {
					item.appear({
						afterFinish: function() {
							item.inProgress = false;
						}.bind(item)
					});
				} else {
					item.fade({
						afterFinish: function() {
							item.inProgress = false;
						}.bind(item)
					});
				}
			}.bind(this));
			
			if (this.navigation.size() > 0) {
				this.navigation.invoke('removeClassName', 'act');
				this.navigation[itemPos].addClassName('act');
			}
		}
	}
});



var smoothScroll = function(event){
	Event.stop(event);
	this.onclick = function() {return false;};
	var target = this.uri[1];
	if($(target)) new Effect.ScrollTo(target, {offset: -24});
}

Event.observe(window,'load',function(){
	$$('.scrollinglink').each(function(item){
		if(item.href && item.href.indexOf('#') > -1){
			item.uri = item.href.split("#");
			item.observe('click', smoothScroll.bind(item));
		}
	});
});



Event.observe(document, "dom:loaded", function (event) {
	$$('.imageslider').each(function (container) {
		new ImageSlide(container);
	});
	
	$$('.slider-box').each( function (container) {
		new SliderBox(container);
	});
});

