// Also known as IE fix
var TridentFix = new Class({
	tridentFix: function(item){
		item.addEvents({
			'mouseover':function(){
				this.addClass('iehover');
			},
			'mouseout':function(){
				this.removeClass('iehover');
			}
		});
	}
});


var DropMenu = new Class({
	Implements: [Options,TridentFix],
	/* 
		don't know about options yet
		but set it up anyways just in case 
	*/
	options: {
		mode: 'horizontal'
	},
	menu: null,
	initialize: function(menu,options){
		if(options) this.setOptions(options);
	
		this.menu = $(menu);
		
		// grab all of the menus children - LI's in this case
		var children = this.menu.getChildren();
		
		// loop through children
		children.each(function(item,index){
			// declare some variables 
			var fChild, list;
			
			/* 
				fChild = first child - which should be an A tag
				list = submenu UL
			*/
			fChild = item.getFirst();
			list = fChild.getNext('ul');
			
			// check if IE, if so apply fix
			if(Browser.Engine.trident) this.tridentFix(item);
			
			// if there is a sub menu UL
			if(list){
				item.mel = list; // pel = parent element
				list.pel = item; // mel = menu element
				new SubMenu(list); // hook up the subMenu
			}
		},this); // binding loop to this object for trident fix

	}	
});



var SubMenu = new Class({
	Implements: [Options,TridentFix],
	/* 
		don't know about options yet
		but set it up anyways just in case 
	*/
	options: {
		mode: 'vertical'
	},
	menu: null, // storage for menu object
	depth: 0, // storage for current menu depth
	initialize: function(el,depth,options){
		if(options) this.setOptions(options); // set options
		if(depth) this.depth = depth;// set depth
		
		this.menu = el; //attach menu to object
		
		if(this.depth == 0)	this.menu.addClass('submenu'); // class for first level
		if(this.depth >= 1)	this.menu.addClass('sub_submenu'); // class for deeper levels - in case :P
		
		this.menu.fade('hide'); // set menu to hid

		/*
			hook up menu's parent with event
			to trigger menu
		*/
		this.menu.pel.addEvents(this.parentEvents); 
		
		// get menu's child elements
		var children = this.menu.getChildren();
			
		// loop through children
		children.each(function(item,index){
			// declare some variables 
			var fChild, list;
			
			/* 
				fChild = first child - which should be an A tag
				list = submenu UL
			*/
			fChild = item.getFirst();
			list = fChild.getNext('ul');
			
			// check if IE, if so apply fix
			if(Browser.Engine.trident) this.tridentFix(item);
			
			// if the menu item has a sub_submenu
			if(list){
				/*
					create marker for menu item
					that has a sub_submenu
					this is to show persistence and 
					where you are in the menu tree
				*/
				var count = new Element('span').set('html','\&raquo;').addClass('counter');
				
				item.adopt(count); // stuff it inside li
				count.fade('hide'); // hide it

				item.mel = list; // mel = menu element
				item.count = count; // attach count accessor to menu item
				list.pel = item; // pel = parent element
				
				// create new subMenu with depth incremented
				new SubMenu(list,this.depth+1);
			}
		},this); //bound to this for trident fix
	},
	// menu parent mouse events
	parentEvents: {
		'mouseover': function(){
			/*
				if it has a count accesor
				then fade it in 
			*/
			if(this.count) this.count.fade('in');
			
			// fade in menu
			this.mel.fade('in');		
		},
		'mouseout': function(){
			/*
				if it has a count accesor
				then fade it out 
			*/
			if(this.count) this.count.fade('out');
			
			// fade out menu
			this.mel.fade('out');
		}
	}
});

Fx.Elements = new Class({

    Extends: Fx.CSS,

    initialize: function(elements, options){
        this.elements = this.subject = $$(elements);
        this.parent(options);
    },

    compute: function(from, to, delta){
        var now = {};
        for (var i in from){
            var iFrom = from[i], iTo = to[i], iNow = now[i] = {};
            for (var p in iFrom) iNow[p] = this.parent(iFrom[p], iTo[p], delta);
        }
        return now;
    },

    set: function(now){
        for (var i in now){
            var iNow = now[i];
            for (var p in iNow) this.render(this.elements[i], p, iNow[p], this.options.unit);
        }
        return this;
    },

    start: function(obj){
        if (!this.check(arguments.callee, obj)) return this;
        var from = {}, to = {};
        for (var i in obj){
            var iProps = obj[i], iFrom = from[i] = {}, iTo = to[i] = {};
            for (var p in iProps){
                var parsed = this.prepare(this.elements[i], p, iProps[p]);
                iFrom[p] = parsed.from;
                iTo[p] = parsed.to;
            }
        }
        return this.parent(from, to);
    }

});

/*
Script: Accordion.js
    An Fx.Elements extension which allows you to easily create accordion type controls.

License:
    MIT-style license.
*/

var Accordion = new Class({

    Extends: Fx.Elements,

    options: {/*
        onActive: $empty,
        onBackground: $empty,*/
//        display: 0,
        show: false,
        height: true,
        width: false,
        opacity: true,
        fixedHeight: false,
        fixedWidth: false,
        wait: false,
        alwaysHide: false
    },

    initialize: function(){
        var params = Array.link(arguments, {'container': Element.type, 'options': Object.type, 'togglers': $defined, 'elements': $defined});
        this.parent(params.elements, params.options);
        this.togglers = $$(params.togglers);
        this.container = $(params.container);
        this.previous = -1;
        if (this.options.alwaysHide) this.options.wait = true;
        if ($chk(this.options.show)){
            this.options.display = false;
            this.previous = this.options.show;
        }
        if (this.options.start){
            this.options.display = false;
            this.options.show = false;
        }
        this.effects = {};
        if (this.options.opacity) this.effects.opacity = 'fullOpacity';
        if (this.options.width) this.effects.width = this.options.fixedWidth ? 'fullWidth' : 'offsetWidth';
        if (this.options.height) this.effects.height = this.options.fixedHeight ? 'fullHeight' : 'scrollHeight';
        for (var i = 0, l = this.togglers.length; i < l; i++) this.addSection(this.togglers[i], this.elements[i]);
        this.elements.each(function(el, i){
            if (this.options.show === i){
                this.fireEvent('active', [this.togglers[i], el]);
            } else {
                for (var fx in this.effects) el.setStyle(fx, 0);
            }
        }, this);
        if ($chk(this.options.display)) this.display(this.options.display);
    },

    addSection: function(toggler, element, pos){
        toggler = $(toggler);
        element = $(element);
        var test = this.togglers.contains(toggler);
        var len = this.togglers.length;
        this.togglers.include(toggler);
        this.elements.include(element);
        if (len && (!test || pos)){
            pos = $pick(pos, len - 1);
            toggler.inject(this.togglers[pos], 'before');
            element.inject(toggler, 'after');
        } else if (this.container && !test){
            toggler.inject(this.container);
            element.inject(this.container);
        }
        var idx = this.togglers.indexOf(toggler);
        toggler.addEvent('click', this.display.bind(this, idx));
        if (this.options.height) element.setStyles({'padding-top': 0, 'border-top': 'none', 'padding-bottom': 0, 'border-bottom': 'none'});
        if (this.options.width) element.setStyles({'padding-left': 0, 'border-left': 'none', 'padding-right': 0, 'border-right': 'none'});
        element.fullOpacity = 1;
        if (this.options.fixedWidth) element.fullWidth = this.options.fixedWidth;
        if (this.options.fixedHeight) element.fullHeight = this.options.fixedHeight;
        element.setStyle('overflow', 'hidden');
        if (!test){
            for (var fx in this.effects) element.setStyle(fx, 0);
        }
        return this;
    },

    display: function(index){
        index = ($type(index) == 'element') ? this.elements.indexOf(index) : index;
        if ((this.timer && this.options.wait) || (index === this.previous && !this.options.alwaysHide)) return this;
        this.previous = index;
        var obj = {};
        this.elements.each(function(el, i){
            obj[i] = {};
            var hide = (i != index) || (this.options.alwaysHide && (el.offsetHeight > 0));
            this.fireEvent(hide ? 'background' : 'active', [this.togglers[i], el]);
            for (var fx in this.effects) obj[i][fx] = hide ? 0 : el[this.effects[fx]];
        }, this);
        return this.start(obj);
    }

});           

var MultiTabs = new Class({
    options:{
        id:'multi-tab',
        className:'multi-tab',
        tabSelector:'.tab',
        pageSelector:'.page'
    },
    Implements:[Events,Options],
    rows:[],
    tabs:[],
    pages:[],
    initialize: function(options){
        this.setOptions(options);
        var pages = $$(this.options.pageSelector);
        if (!pages) return;
        this.tabsContainer = new Element('div',{'class':'tabs-container column-container'});      
        this.pagesContainer = new Element('div',{'class':'pages-container'}); 
        this.container = new Element('div',{'class':this.options.className,'id':this.options.id});
        this.container.adopt(this.tabsContainer,this.pagesContainer);
        this.selectedIndex = 0; 
        $$(this.options.tabSelector).each(function(tab, index){
            this.createTab(tab, pages[index]);   
        },this); 
    },
    createTab: function(tab, page){
        tab = $(tab);
        page = $(page);
        var className = tab.get('class'), matches, row = 0, aTab, aButton;
        if (className && (matches = className.match(/tab-row-(\d)/i))) {
            row = matches[1].toInt();   
        }
        while (this.rows.length <= row){
            this.rows.push(new Element('ul',{'class':'tab-row column-container'}).inject(this.tabsContainer));
        }
        aTab = new Element('li',{'class':'tab-container'})
            .adopt(new Element('div',{'class':'button-container'})
            .adopt(new Element('a',{'class':'button','events':{'click':this.tabClicked.bind(this,[this.tabs.length])}})
            .adopt(aButton = new Element('span',{'class':'button-content'})
            .adopt(new Element('span',{'class':'button-label','html':tab.get('html')})))));
        if (tab.get('style')){
            aButton.set('style',tab.get('style'));
        }
        if (tab.get('id')){
            aTab.set('id',tab.get('id'));
        }
        this.rows[row].adopt(aTab);
        this.tabs.push(aTab);
        this.pages.push(page);
        this.pagesContainer.adopt(page);
        page.setStyle('display','none');
        tab.dispose();
    },
    tabClicked:function(index){
        //var ul = this.tabs[index];
        //alert(ul.getElement('.button-label').getStyle('margin-right'));
        this.selectTab(index);   
    },
    selectTab:function(index){
        this.tabs[this.selectedIndex].removeClass('selected');
        this.pages[this.selectedIndex].setStyle('display','none');
        this.selectedIndex = index;
        this.tabs[this.selectedIndex].addClass('selected');
        this.pages[this.selectedIndex].setStyle('display','block');
        this.tabsContainer.getLast().removeClass('selected')
        this.tabsContainer.adopt(this.tabs[this.selectedIndex].getParent());
        this.tabsContainer.getLast().addClass('selected')
        return this;
    },
    addTo: function(element){
        $(element).adopt(this.container);
        return this;
    },
    fitTabs: function() {
        this.rows.each(this.fitTabRow,this);
        return this;
    },
    fitTabRow: function(ul) {
        var width = ul.offsetWidth;
        var lis = ul.getChildren();
        lis.getLast().getElement('a.button').setStyles({
            'margin-right':'0px',
            'padding-right':'0px'
        });
        lis.each(function(li){
            width -= li.offsetWidth;
        });
        var diff = Math.floor(width / lis.length)
        lis.each(function(li, index){
            var el = li.getElement('.button-label');
            var w = el.getStyle('width').toInt();
            var newWidth = ((index == lis.length-1) ? w+width : w+diff);
            el.setStyle('width',newWidth +'px');
            width -= diff;
        })
        return this;
    },
    addPseudoClasses: function() {
        this.rows.each(function(ul){
            ul.getChildren('li').removeClass('first-child').removeClass('last-child');
            ul.getFirst('li').addClass('first-child');
            ul.getLast('li').addClass('last-child');
        });
        return this;
    }
});
function enableImageZoom(selector){
        var currentNormal;
        var currentOver;
        $$(selector).each(function(link){
            var imgNormal = link.getElement('img');
            if (!imgNormal){
                return;
            }
            var imgOver = new Element('img',{
                'class':'zoom',
                'styles':{
                    'position':'absolute',
                    'display':'none',
                    'width':'69px',
                    'height':'25px',
                    'cursor':'pointer'
                },
                'src':imgNormal.get('src').replace('_sw.jpg','.jpg')
            }).inject(document.body);
            imgOver.set('morph',{link:'cancel','onComplete':function(){
                if (imgOver.getStyle('margin-left').toInt() == 0){
                    imgNormal.setStyle('visibility','visible');
                    imgOver.setStyle('display','none');
                    currentNormal = currentOver = null;
                }
            }});
            imgOver.addEvent('mouseleave',function(){
                //currentOver = imgOver;
                imgOver.morph({
                    'width':'69px',
                    'height':'25px',
                    'margin-left':0,
                    'margin-top':0
                })
            });
            imgOver.addEvent('click',function(){
                window.location.href = link.get('href');
            })
            //console.log(imgNormal, imgOver, imgNormal.getPosition());
            link.addEvents({
                'mouseenter':function(){
                    if (currentNormal){
                        currentNormal.setStyle('visibility','visible');
                    }
                    if (currentOver){
                        currentOver.morph({
                            'width':'69px',
                            'height':'25px',
                            'margin-left':0,
                            'margin-top':0
                        })
                        //currentOver.setStyle('display','none');
                    }
                    var position = imgNormal.getPosition();
                    //alert(position.y);
                    imgOver.setStyles({
                        'display':'block',
                        'left':position.x+'px',
                        'top':position.y+'px',
                        'width':'69px',
                        'height':'25px',
                        'margin-left':0,
                        'margin-top':0
                    });
                    imgNormal.setStyle('visibility','hidden');
                    imgOver.morph({
                        'width':[69,110],
                        'margin-left':[0,-20],
                        'margin-right':[0,-19],
                        'height':[25,42],
                        'margin-top':[0,-8],
                        'margin-bottom':[0,-9]
                    });
                    currentNormal = imgNormal;
                    currentOver = imgOver;
                }
            })
        })
}
window.addEvent('load',function() {
    if ($('multi-tabs-container')) {
        var tabs1 =  new MultiTabs({
            'tabSelector':'#multi-tabs-container .tab',
            'pageSelector':'#multi-tabs-container .page'
        }).addTo('multi-tabs-container').addPseudoClasses().selectTab(0).fitTabs();
        enableImageZoom('#multi-tabs-container .page a');
    }
    if ($('multi-tabs-container-2')) {  
        var tabs2 = new MultiTabs({
            'tabSelector':'#multi-tabs-container-2 .tab',
            'pageSelector':'#multi-tabs-container-2 .page',
            'id':'multi-tabs-2'
        }).addTo('multi-tabs-container-2').addPseudoClasses().selectTab(0).fitTabs();
    }
    if ($('multi-tabs-container-3')) {  
        var tabs3 = new MultiTabs({
            'tabSelector':'#multi-tabs-container-3 .tab',
            'pageSelector':'#multi-tabs-container-3 .page',
            'id':'multi-tabs-3'
        }).addTo('multi-tabs-container-3').addPseudoClasses().selectTab(0).fitTabs();
        enableImageZoom('#multi-tabs-container-3 .page a');
    }
    if ($('multi-tabs-container-4')) {  
        var tabs3 = new MultiTabs({
            'tabSelector':'#multi-tabs-container-4 .tab',
            'pageSelector':'#multi-tabs-container-4 .page',
            'id':'multi-tabs-4'
        }).addTo('multi-tabs-container-4')/*.addPseudoClasses()*/.selectTab(0)/*.fitTabs()*/;
    }

    if (section == 'kontakt') {
        
        // Anpassung IE6
        if(window.ie6) var heightValue='100%';
        else var heightValue='';

        // Selektoren der Container für Schalter und Inhalt
        var togglerName='h1.toggler_';
        var contentName='div.content_';


        // Selektoren setzen
        var counter=1;   
        var toggler=$$(togglerName+counter);
        var content=$$(contentName+counter);
        while(toggler.length>0)
        {
          // Accordion anwenden
          if (counter>1) index=false;
          new Accordion(toggler, content, index, {
             opacity: false,
             display: index,
             alwaysHide: true,
             onComplete: function() { 
                var element=$(this.elements[this.previous]);
                if(element && element.offsetHeight>0) element.setStyle('height', heightValue);         
             },
             onActive: function(toggler, content) {
                toggler.addClass('open');
             },
             onBackground: function(toggler, content) {
                toggler.removeClass('open');
             }
          });

          // Selektoren für nächstes Level setzen
          counter++;
          toggler=$$(togglerName+counter);
          content=$$(contentName+counter);
        }
    }
    
});
