var fadeDuration = 'slow';
var _activeCounter = 0;
var _countElements = 0;
var _arrElements = [];
function initPaging(){
     $('a.paging-link').click(function(){
                $("#ajax-load-dest").load($(this).attr('href') + ' #modeldetail',
                function(response, status, xhr){
                    initPaging();
                    initGalleryLinkBack();
                    initToolTips();                    
                    trackEventPageView();                    
                });
                return false;
            });
}


function trackEventPageView(){
	try{
	    var title = $('#page-info-title').val();	
	    var url = $('#page-info-url').val();
	    var desc = $('#page-info-desc').val();   	   	 	
		pageTracker._trackEvent(desc, title, url);
		
	} catch(err) {}
	
	
}
function fancyGroessen(){

	$("a.groessentabelle").fancybox({
		type : 'iframe',

		padding : 0,
		margin : 0,
		autoScale : true,
		autoDimension : true,
		scrolling : 'no',
		overlayOpacity : 0.8,
		overlayColor : '#000',
		onComplete : function() {
			$('#fancybox-inner').css('width', '600px');
			$('#fancybox-wrap').css('width', '600px');
			$('#fancybox-inner').css('height', '500px');
			$('#fancybox-wrap').css('height', '500px');
			$.fancybox.center();
		}
	});


}

function initToolTips(){
    //$("#functionLevelToolTip img").tooltip({
    //    tipClass:   'tooltip-ajax'
    //});
}
function initGalleryLinkBack(){
    $('a.gallery-link').click(function(){
        $("#ajax-load-dest").load($(this).attr('href') + ' .tab-gallery',
        function(response, status, xhr){
            $('#modeldetail').fadeOut(fadeDuration);
            $('.tab-gallery').css('display','none');
            $('.tab-gallery').fadeIn(fadeDuration);
            initDetailLink();
            initGalleryTop();
            initToolTips();
        });
        return false;
    });
}

function initThumbnailLink(){
	
    $('a.tab').click(function(){
        $("#ajax-load-dest").load($(this).attr('href') + ' .tab-gallery',
        function(response, status, xhr){
            //$('#modeldetail').fadeOut(fadeDuration);
            //$('.tab-gallery').css('display','none');
            //$('.tab-gallery').fadeIn(fadeDuration);
            initDetailLink();
            initGalleryTop();
            initToolTips();
            trackEventPageView();  
        });
        return false;
    });
}


function initDetailLink(){
    $('a.details-link').click(function(){
        $("#ajax-load-dest").load($(this).attr('href') + ' #modeldetail',
        function(response, status, xhr){
             $('.tab-gallery').fadeOut(fadeDuration);
             $('#modeldetail').css('display','none');
             $('#modeldetail').fadeIn(fadeDuration);
             initPaging();
             initGalleryLinkBack();
             initToolTips();
             fancyGroessen();
             trackEventPageView();  

        });
        return false;
    });
}

function initGallery(){
	$('div.gallery').gallery({
		duration: 500,
		infinite:true,
		listOfSlides: 'div.hold > ul > li'
	});

	$('.details-link').click(function(){
	  $('.tab-gallery').fadeOut('fast',function(){
	    $('#modeldetail').fadeIn('fast');
	  });

	});

	$('.gallery-link').click(function(){
    $('#modeldetail').fadeOut('fast',function(){
      $('.tab-gallery').fadeIn('fast');
    });
  });

	$('div.gal').each(function(){
		$(this).gallery({
			duration: 500,
			infinite:true,
			nextBtn: 'a.btn-gal-next',
			prevBtn: 'a.btn-gal-prev',
			listOfSlides: 'ul > li',
			before:function($this){
				$this.list.parents('div.hold').find('div.tooltip div.box ul li:eq(0) a').text($this.active-$this.count+1);
				$this.list.parents('div.hold').find('div.tooltip div.box ul li:eq(1) a').text($this.count);
			},
			after:function($this){
				var a = $this.active;
				var c = $this.count;
				var t = a-c+1;
				if(t == c+1) t = 1;
				$this.list.parents('div.hold').find('div.tooltip div.box ul li:eq(0) a').text(t);
				$this.list.parents('div.hold').find('div.tooltip div.box ul li:eq(1) a').text($this.count);
			}
		});
	});
}

function initGalleryTop(){
    initSlideCounter();
    $('div.gal').each(function(){
		$(this).gallery({
			duration: 500,
			infinite:true,
			nextBtn: 'a.btn-gal-next',
			prevBtn: 'a.btn-gal-prev',
			listOfSlides: 'ul > li',
			before:function($this){
				$this.list.parents('div.hold').find('div.tooltip div.box ul li:eq(0) a').text($this.active-$this.count+1);
				$this.list.parents('div.hold').find('div.tooltip div.box ul li:eq(1) a').text($this.count);
			},
			after:function($this){
				var a = $this.active;
				var c = $this.count;
				var t = a-c+1;
				if(t == c+1) t = 1;
				$this.list.parents('div.hold').find('div.tooltip div.box ul li:eq(0) a').text(t);
				$this.list.parents('div.hold').find('div.tooltip div.box ul li:eq(1) a').text($this.count);
			}
		});
	});
}

function initSlideCounter(){
    countElements();
    setFunctionLevel(0);
    _activeCounter = 0;
    $('.btn-gal-prev').click(function(){
        if(_activeCounter != 0){
            _activeCounter--;
        }else{
            _activeCounter = _countElements -1;
        }
        setFunctionLevel(_activeCounter);
    });
    $('.btn-gal-next').click(function(){
       if(_activeCounter < _countElements -1){
           _activeCounter++;
       }else{
           _activeCounter = 0;
       }
       setFunctionLevel(_activeCounter);
    });
}

function setFunctionLevel(count){
    var link = $(_arrElements[count]).find('a').attr("href");
    var cssValue = 'url('+link+')';
    $('.btn-gal').css('background-image',cssValue);
}

function countElements(){
    _countElements = 0;
    _arrElements = [];
    $('.gallery-top').find('li').each(function(){_arrElements.push(this);});
    _countElements = _arrElements.length;
}

function initLaguageNote(){
	 $("a.lightbox_language_link").fancybox({
			type            : 'iframe',
         autoScale       : true,
         autoDimension   : true,
         scrolling       : 'no',
         margin          : 0,
         padding         : 0,
         overlayColor    : '#000',
         overlayOpacity	: 0.7,
         onComplete      : function(){
 
 $('#fancybox-inner').css('width','480px');
 $('#fancybox-wrap').css('width','480px');
 $('#fancybox-inner').css('height','320px');
 $('#fancybox-wrap').css('height','320px');
 $.fancybox.center();
 
}  
});
	
}

$(window).load(function() {
    
    initThumbnailLink();
    initDetailLink();
    initSlideCounter();
    initLaguageNote();

});

$(function(){
    initGallery()
});

(function($) {
	$.fn.gallery = function(options) { return new Gallery(this.get(0), options); };
	function Gallery(context, options) { this.init(context, options); };
	Gallery.prototype = {
		options:{},
		init: function (context, options){
			this.options = $.extend({
				infinite: false,								//true = infinite gallery
				duration: 700,									//duration of effect it 1000 = 1sec
				slideElement: 1,								//number of elements for a slide
				autoRotation: false,							//false = option is disabled; 1000 = 1sec
				effect: false,									//false = slide; true = fade
				listOfSlides: 'ul > li',						//elements galleries
				switcher: false,								//false = option is disabled; 'ul > li' = elements switcher
				disableBtn: false,								//false = option is disabled; 'hidden' = class adds an buttons "prev" and "next"
				nextBtn: 'a.link-next, a.btn-next, a.next',		//button "next"
				prevBtn: 'a.link-prev, a.btn-prev, a.prev',		//button "prev"
				circle: true,									//true = cyclic gallery; false = not cyclic gallery
				direction: false,								//false = horizontal; true = vertical
				event: 'click',									//event for the buttons and switcher
				IE: false,										//forced off effect it "fade" in IE
				autoHeight: false,								//auto height on fade
				before:function(){},
				after:function(){}
			}, options || {});
			var _el = $(context).find(this.options.listOfSlides);
			if (this.options.effect) this.list = _el;
			else this.list = _el.parent();
			this.switcher = $(context).find(this.options.switcher);
			this.nextBtn = $(context).find(this.options.nextBtn);
			this.prevBtn = $(context).find(this.options.prevBtn);
			this.count = _el.index(_el.filter(':last'));
			
			if (this.options.switcher) this.active = this.switcher.index(this.switcher.filter('.active:eq(0)'));
			else this.active = _el.index(_el.filter('.active:eq(0)'));
			if (this.active < 0) this.active = 0;
			this.last = this.active;
			
			this.woh = _el.outerWidth(true);
			if (!this.options.direction) this.installDirections(this.list.parent().width());
			else {
				this.woh = _el.outerHeight(true);
				this.installDirections(this.list.parent().height());
			}
			
			if (!this.options.effect) {
				this.rew = this.count - this.wrapHolderW + 1;
				if (!this.options.direction) this.anim = '{marginLeft: -(this.woh * this.active)}';
				else this.anim = '{marginTop: -(this.woh * this.active)}';
				eval('this.list.css('+this.anim+')');
			}
			else {
				this.rew = this.count;
				this.list.css({opacity: 0}).removeClass('active').eq(this.active).addClass('active').css({opacity: 1}).css('opacity', 'auto');
				this.switcher.removeClass('active').eq(this.active).addClass('active');
				if(this.options.autoHeight) this.list.parent().css({height: this.list.eq(this.active).outerHeight()});
			}
			this.flag = true;
			if (this.options.infinite){
				this.count++;
				this.active += this.count;
				this.list.append(_el.clone());
				this.list.append(_el.clone());
				eval('this.list.css('+this.anim+')');
			}
			
			this.initEvent(this, this.nextBtn, true);
			this.initEvent(this, this.prevBtn, false);
			if (this.options.disableBtn) this.initDisableBtn();
			if (this.options.autoRotation) this.runTimer(this);
			if (this.options.switcher) this.initEventSwitcher(this, this.switcher);
			this.options.before(this);
		},
		initDisableBtn: function(){
			this.prevBtn.removeClass('prev-'+this.options.disableBtn);
			this.nextBtn.removeClass('next-'+this.options.disableBtn);
			if (this.active == 0 || this.count+1 == this.wrapHolderW) this.prevBtn.addClass('prev-'+this.options.disableBtn);
			if (this.active == 0 && this.count == 1 || this.count+1 <= this.wrapHolderW) this.nextBtn.addClass('next-'+this.options.disableBtn);
			if (this.active == this.rew) this.nextBtn.addClass('next-'+this.options.disableBtn);
		},
		installDirections: function(temp){
			this.wrapHolderW = Math.ceil(temp / this.woh);
			if (((this.wrapHolderW - 1) * this.woh + this.woh / 2) > temp) this.wrapHolderW--;
		},
		fadeElement: function(){
			if ($.browser.msie && this.options.IE){
				this.list.eq(this.last).css({opacity:0});
				this.list.removeClass('active').eq(this.active).addClass('active').css({opacity:'auto'});
			}
			else{
				this.list.eq(this.last).animate({opacity:0}, {queue:false, duration: this.options.duration});
				this.list.removeClass('active').eq(this.active).addClass('active').animate({
					opacity:1
				}, {queue:false, duration: this.options.duration, complete: function(){
					$(this).css('opacity','auto');
				}});
			}
			if(this.options.autoHeight) this.list.parent().animate({height: this.list.eq(this.active).outerHeight()}, {queue:false, duration: this.options.duration});
			if (this.options.switcher) this.switcher.removeClass('active').eq(this.active).addClass('active');
			this.last = this.active;
		},
		scrollElement: function($this){
			if (!$this.options.infinite) eval('$this.list.animate('+$this.anim+', {queue:false, duration: $this.options.duration});');
			else eval('$this.list.animate('+$this.anim+', $this.options.duration, function(){ $this.flag = true });');
			if ($this.options.switcher) $this.switcher.removeClass('active').eq($this.active / $this.options.slideElement).addClass('active');
			this.options.after($this);
		},
		runTimer: function($this){
			if($this._t) clearTimeout($this._t);
			$this._t = setInterval(function(){
				if ($this.options.infinite) $this.flag = false;
				$this.toPrepare($this, true);
			}, this.options.autoRotation);
		},
		initEventSwitcher: function($this, el){
			el.bind($this.options.event, function(){
				$this.active = $this.switcher.index($(this)) * $this.options.slideElement;
				if($this._t) clearTimeout($this._t);
				if ($this.options.disableBtn) $this.initDisableBtn();
				if (!$this.options.effect) $this.scrollElement($this);
				else $this.fadeElement();
				if ($this.options.autoRotation) $this.runTimer($this);
				return false;
			});
		},
		initEvent: function($this, addEventEl, dir){
			addEventEl.bind($this.options.event, function(){
				if ($this.flag){
					if ($this.options.infinite) $this.flag = false;
					if($this._t) clearTimeout($this._t);
					$this.toPrepare($this, dir);
					if ($this.options.autoRotation) $this.runTimer($this);
				}
				return false;
			});
		},
		toPrepare: function($this, side){
			if (!$this.options.infinite){
				if (($this.active == $this.rew) && $this.options.circle && side) $this.active = -$this.options.slideElement;
				if (($this.active == 0) && $this.options.circle && !side) $this.active = $this.rew + $this.options.slideElement;
				for (var i = 0; i < $this.options.slideElement; i++){
					if (side) { if ($this.active + 1 <= $this.rew) $this.active++; }
					else { if ($this.active - 1 >= 0) $this.active--; }
				};
			}
			else{
				if ($this.active >= $this.count + $this.count && side) $this.active -= $this.count;
				if ($this.active <= $this.count-1 && !side) $this.active += $this.count;
				eval('$this.list.css('+$this.anim+')');
				if (side) $this.active += $this.options.slideElement;
				else $this.active -= $this.options.slideElement;
			}
			if (this.options.disableBtn) this.initDisableBtn();
			if (!$this.options.effect) $this.scrollElement($this);
			else $this.fadeElement();
		},
		stop: function(){
			if (this._t) clearTimeout(this._t);
		},
		play: function(){
			if (this._t) clearTimeout(this._t);
			if (this.options.autoRotation) this.runTimer(this);
		}
	}
}(jQuery));
