/**
 * @author Andreask
 */
var Circle = new Class({
	Extends: Fx,
	initialize: function(element, carousel, options){
		this.element = this.subject = $(element);
		this.parent(options);
		this.now = 0;
		this.first = false;
		element.addEvent('click', this.moveCarousel.pass(carousel, this));
		$$('.hideAccordion')[0].setStyle('display', 'none');
		//element.getElement('a').addEvent('click', this.stopLink.bindWithEvent(this));
		var inactiveFooter = element.getElement('div.inactive');
		if (inactiveFooter) {
			var tooltip = inactiveFooter.getElement('p')
			inactiveFooter.getElements('span.topLeft, p').addEvents({
				'mouseenter': this.showTooltip.pass(tooltip, this),
				'mouseleave': this.hideTooltip.pass(tooltip, this)
			});
		}
	},
	/**
	 * Geht um steps oder 60 grad weiter
	 * @param {Object} to
	 */
	goTo: function(steps){
		this.now %= 360; 
		var to = this.now + steps;
		if(to%360 <=180 && to % 360 != 0){
			to +=  120;
		}
		this.start(this.now, to);
		return(this);
	},
	/**
	 * Überschreibt set in Fx 
	 * @param {Object} value
	 */
	set: function(value){
		value = Math.floor(value);
		this.now = value;
		value %= 360;
		this.first = value === 0;
		var coord = this.options.coords[value];
		this.element.setStyles({
			'top': coord.y,
			'left': coord.x,
			'fontSize': 0.84 + Math.pow((Math.abs(value - 180)/180), 5) * 0.16 + 'em',
			'zIndex': Math.abs(value - 180)+10
			
		});
		return this;
	},
	moveCarousel: function(carousel){
		if(!this.first){
			carousel.moveBoxes(360 - (this.now % 360));
		}
	},
	stopLink: function(event){
		if (!this.first) {
			event.preventDefault();
		}
	},
	showTooltip: function(tooltip){
		if (this.first) {
			tooltip.fade('in');
		}
		if(this.tooltipTimer){
			$clear(this.tooltipTimer);
		}
	},
	hideTooltip: function(tooltip){
		this.tooltipTimer = function(){
			tooltip.fade('out')
		}.delay(300);
	}
});

var Carousel = new Class({
	initialize: function(){
		this.boxes = [];
		var coords = this.calcCoords(),
			fontSize= ['1em', '0.86', '0.84em', '0.84em'];
		$$('div.box').each(function(box, cnt){			
			var contentBox = box.getElement('div.contentBox'),
				hideAccordion = box.getElement('.hideAccordion'),
				content = box.getElement('div.content').getChildren(),
				boxes = box.getElement('div.contentBox, div.contentBox div');
			content.push(box.getElement('div.footer span.topLeft'))
			this.boxes.push(
				new Circle(box, this, {
					coords: coords, 
					onStart: function(){
						boxes.setStyle('overflow','hidden');
						hideAccordion.setStyle('display', 'block');
						if (Browser.Engine.trident && Browser.Engine.version == 5) {
							boxes.setStyle('overflow','auto');
						};
					},
					onComplete: function(){
						boxes.setStyle('overflow', this.first ? 'auto' : 'hidden');
						content.setStyle('opacity', this.first ? 1 : 0.3);
						hideAccordion.setStyle('display', this.first ? 'none' : 'block');
						if (Browser.Engine.trident && Browser.Engine.version == 5) {
							boxes[0].parentNode.setStyle('margin-right', this.first ? '-2.3em' : '-2.2em');
						};
					}
				})
				.set(360 - cnt * 60)
			);
			box.setStyles({
				'opacity': Browser.Engine.trident  ? 1 : 0,
				'fontSize': '0em',
				'top':  $random(0, 20),
				'left': $random(200, 400),
				'zIndex': 10 - cnt
			});
			content.setStyle('opacity', cnt === 0 ? 1 : 0.3);
			var boxes = box.getElements('div.contentBox, div.contentBox div');

			var myEffect = new Fx.Morph(box, {
					duration: 1500, 
					onStart: function(){			
						boxes.setStyle('overflow', 'hidden'); 
						if ((cnt !== 0) && (Browser.Engine.trident && Browser.Engine.version == 5)) {
								boxes[0].parentNode.setStyle('margin-right', '-2.2em');
						}						
					},
					onComplete: function(){
						if (cnt == 0) {
							boxes.setStyle('overflow', 'auto');
						}
					}
				}),
				coord = coords[360 - cnt * 60];
			myEffect.start({
				'top': coord.y,
				'left': coord.x,
				'opacity': 1
			});
			var myFx = new Fx.Tween(box, {
				unit: 'em'
				});
			myFx.start('fontSize', 0, fontSize[cnt]);
		}, this)
		
		var tooltip = $$('.contentBox .tooltip');
		var tooltipText =  $$('.contentBox p.tooltiptext')
		tooltip.each(function(tt, cnt){
			tt.set('title', tooltipText[cnt].get('html'));
		})
		tooltipText.dispose();
		var t = new Tips(tooltip, {className: 'offerTooltip'});
		
	},
	/**
	 * Coordinaten für die Ellipse berechnen, bekommt jeder Circle dann mit
	 */
	calcCoords: function(){
		coords = [];
		var TWOPI = Math.PI * 2,
			a=300, 
			b=50,
			centerX = 170,
			centerY = 120,
			offset = .55;
		for (var t = Math.PI / 2 + offset, steps = TWOPI / 360, i = 0; i <= 360; t += steps, i ++) {
			coords[i] = {
				x: a * Math.cos(t) + centerX,
				y: b * Math.sin(t) + centerY
			};
		}
		return coords;
	},
	/**
	 * Alle Boxen um steps weiter bewegen
	 * @param {Object} steps
	 */
	moveBoxes: function(steps){
		this.boxes.each(function(box){
			box.goTo(steps)
		});
	}
});

var Star = new Class({
	initialize: function(){
		var star = $('star');
		star.addEvents({
			'mouseenter': this.toggle.pass([200, star]),
			'mouseleave': this.toggle.pass([80, star])
		})
		.set('tween', {transition: Fx.Transitions.Elastic.easeOut});
	},
	toggle: function(width, star){
		star.get('tween', {property: 'width'}).start(width)
	}	
});

var Clock = new Class({
	implement: Options,
	initialize: function(timeLeft){
		this.timeLeft= timeLeft;
		this.timeContainer = [$('second'), $('minute'), $('hour')];
		this.count.periodical(1000, this);
	},
	count: function(){
		this.timeLeft --;
		var time = [this.timeLeft % 60];
		time[1] = Math.floor((this.timeLeft - time[0]) / 60) % 60;
		time[2] = Math.floor((this.timeLeft - time[0] - time[1] * 60) / 3600);
		this.timeContainer.each(function(container, cnt){
			container.set('text', this.addNull(time[cnt]));
		}, this);
		if(this.timeLeft === 0){
			window.location.reload();
		}
	},
	addNull: function(number){
		return number<10 ? '0' + number : number; 
	}
});

/**
 * Layer (Newsletter, Empfehelen) über Button ein/ausblenden
 * toggle kann auch direkt beim start aufgerufen werden wennn es eine Fehler/Bestätigungsmeldung
 * nach abschicken eines Formulars gibt 
 */
var Buttons = new Class({
	initialize: function(layer){
        layer = $('stage') || layer;
		this.links = [];
		$$('#buttonList a, #privacyLink').each(function(link){
            var href =link.get('href').split('#')[1];
            if(href){
                link.addEvent('click', this.toggle.bindWithEvent(this, $(href.replace('#', '')).set('tween')));
                this.links.push(link);
            }
		}, this);
		var buttonLinks = $$('#buttonList a');
		this.actualForm = layer.set('tween');
		var locationHash = document.location.hash.split('#')[1];
		if (locationHash == 'newsletter' || locationHash == 'recommend' || locationHash == 'privacy') {
				this.toggle(null, $(locationHash))
		}
	},
	toggle: function(event, actualForm){
		if(event){
			event.stop();
		}
		if(Browser.Engine.trident){
			this.actualForm.style.display = 'none';
			actualForm.style.display = 'block';
		}else{
			this.actualForm.get('tween', {
				property: 'opacity'
			}).start(0).chain(function(){
				actualForm.get('tween', {
					property: 'opacity'
				}).start(1);
			});
		}
		if($$('#buttonList li').length>1){
			$$('#buttonList li').toggleClass('hide');
		}
		

		this.actualForm = actualForm;
	}
})

var Animation = new Class({
	initialize: function(isFlash, timeToStart, layer){
		if (Browser.Plugins.Flash.version >= 8 && isFlash) {
			$(document.body).addClass('hasFlash');
			var obj = new Swiff('/pbmedia/happyhour/happyhour_prekredit1003_intro.swf', {
				id: 'happyHour',
				width: 875,
				height: 570,
				wmode: 'transparent',
				callBacks: {
					startAnimation: this.start.bind(this)
				}
			});
			obj.inject($('stage'), 'top');
		} else {
			this.start();
		}
		var b = new Buttons(layer);
		if(layer){
			b.toggle(null, layer);
		}
		var c = new Clock(timeToStart);
	},
	start: function(){
		$$('body')[0].removeClass('flashActive');
		
        if($('stage')){
			this.createAccordion($$('#conditionWidget div.jsAccordion h4'), $$('#conditionWidget div.jsAccordion .contentBox'));
			this.createAccordion($$('#happyHourWidget div.jsAccordion h4'), $$('#happyHourWidget div.jsAccordion .contentBox'));
            var c = new Carousel();
        }
		var flash = $('happyHour');
		if(flash){
			if(Browser.Engine.gecko && Browser.Engine.version <19 ){
				flash.setStyle('display', 'none')
			}else{
				$('stage').removeChild(flash)
			}
		}
	},
	createAccordion: function(togglers, toggle){
            var a = new Accordion(togglers, toggle,{
                show: 0,
                onStart: function(){
                    for(var i=0; i<this.togglers.length; i++){
						this.togglers[i][(i === this.previous ? 'add' : 'remove') + 'Class']('hover');
					}
                    if(Browser.Engine.gecko){
                    this.elements.getElements('div').each(function(div){
                        div.setStyle('overflow', 'hidden')
                    })
                    }

                },
                onComplete: function(){
                    if(Browser.Engine.gecko){
                        this.elements.getElements('div').each(function(div){
                        div.setStyle('overflow', 'auto')
                    })
                    }
                }
            });
            a.togglers[0].addClass('hover');
			if (Browser.Engine.trident && Browser.Engine.version < 7) {
				togglers.addEvents({
					'mouseenter': function(){
						this.addClass('hover')
					},
					'mouseleave': function(e){
						if(this != a.togglers[a.previous]){
							this.removeClass('hover')
						}
					}
				})
			} 
	}
	
});

