/**
 * jQuery.fn.sortElements
 * --------------
 * @author James Padolsey (http://james.padolsey.com)
 * @version 0.11
 * @updated 18-MAR-2010
 * --------------
 * @param Function comparator:
 *   Exactly the same behaviour as [1,2,3].sort(comparator)
 *   
 * @param Function getSortable
 *   A function that should return the element that is
 *   to be sorted. The comparator will run on the
 *   current collection, but you may want the actual
 *   resulting sort to occur on a parent or another
 *   associated element.
 *   
 *   E.g. $('td').sortElements(comparator, function(){
 *      return this.parentNode; 
 *   })
 *   
 *   The <td>'s parent (<tr>) will be sorted instead
 *   of the <td> itself.
 */
jQuery.fn.sortElements = (function(){
    var sort = [].sort;
    return function(comparator, getSortable) {
        getSortable = getSortable || function(){return this;};
        var placements = this.map(function(){
            var sortElement = getSortable.call(this),
                parentNode = sortElement.parentNode,
                // Since the element itself will change position, we have
                // to have some way of storing it's original position in
                // the DOM. The easiest way is to have a 'flag' node:
                nextSibling = parentNode.insertBefore(
                    document.createTextNode(''),
                    sortElement.nextSibling
                );
            return function() {
                if (parentNode === this) {
                    throw new Error(
                        "You can't sort elements if any one is a descendant of another."
                    );
                }
                // Insert before flag:
                parentNode.insertBefore(this, nextSibling);
                // Remove flag:
                parentNode.removeChild(nextSibling);
            };
        });
        return sort.call(this, comparator).each(function(i){
            placements[i].call(getSortable.call(this));
        });
    };
})();

jQuery.fn.mostVisible = function(mySelector) {
	
	var wHeight = $(window).height()
	var wTop = $(window).scrollTop();
	var wBottom = wTop + wHeight;
	
	most_visible_height = 0;
	$most_visible = false;
	
	if(wTop < 100) return $(this).children(mySelector+':first');
	
	$(this).children(mySelector).each(function(){
		$this = $(this);
		var pHeight = $this.height()
		var pTop = $this.offset().top;
		var pBottom = pTop + pHeight;
		// outside screen at bottom or outside screen at top
		if( pTop > wBottom || pBottom < wTop ) return;
		// part of project visible
		intersect_top = (pTop < wTop) ? wTop : pTop
		intersect_bottom = (pBottom < wBottom) ? pBottom : wBottom
		intersect_height = intersect_bottom - intersect_top;
		if(intersect_height > most_visible_height) {
			$most_visible = $this;
			most_visible_height = intersect_height;
		}
		
	});

	return $most_visible;
}


function homepageAnimation() {

	$('div.big_feature, div.small_feature').addClass('noborder');

	$bi = $('div.big_inner:first');

	$bit = $bi.children('div.text');
	$bit.css({ left: $bit.width() * -1 -40 });

	$sfi = $('#small_features div.feature_row div.small_feature div.sf_image'); //.css('border','1px solid red');
	
	$sfi.each(function(){
		$this = $(this);
		$this.css({
			height: $this.height()+'px',
			width: $this.width()+'px',
			position: 'relative',
			overflow: 'hidden'
		});
	});
	
	$s = $(' div.feature_row:first div.small_feature div.sf_image img');
	
	$s.each(function(){
		// console.log($(this).position().left);
		$(this).css({
			top: $(this).height(),
			// left: $(this).position().left,
			position: 'absolute'	
		});
	});

	ct = 1;	
	
	var biFadeSpeed = ($bi.length) ? 500 : 0;
	
	$bi.css('height', $bi.height()+'px');
	$bi.children('img').hide();
	
	animate_hp = function(){
		$bi.children('img').fadeIn(biFadeSpeed, function(){
			$bit.animate({left: 0 }, 250);
			$s.each(function(){
				$(this).delay(ct*150).animate({ top: 0 }, 200);
				ct++;
	// 			if(ct == $s.length) {
	// 				setTimeout(function(){
	// 					$('div.big_feature, div.small_feature').removeClass('noborder');
	// 				}, 700);
	// 			}
			});
		});	
	}


	
// 	if($bi.length) $image_to_wait_for = $('div.big_feature:first img');
// 	else $image_to_wait_for = $('div.small_feature:first div.sf_image img');
// 	console.log($image_to_wait_for);

	setTimeout(animate_hp, 250);
	
	
}


$(document).ready(function(){




	// set up submenu
	
	// none active - set first active
	if( !$('#submenu a.active').length ) $('#submenu li:first a').addClass('active');
	
	var paddingTO = true;
	
	function adjustPadding() {
		var additionalPadding;
		$scrolltitle = $('div.scrolltitle:last');
		if($scrolltitle.length) {
			additionalPadding = $(window).height() - $('#navigation').height() - $scrolltitle.height();
			if(additionalPadding < 240) additionalPadding = 240;
		} else if( $('#images').length ) {
			additionalPadding = $(window).height() - $('#navigation').height() - $('#information').height() - 31;
		} else {
			additionalPadding = 240;
		}
		$('#content').css( 'padding-bottom', additionalPadding );
	}
	

	adjustPadding();
	setTimeout(adjustPadding,100)
	
	var resizeTimer;
	$(window).resize(function() {
		clearTimeout(resizeTimer);
		resizeTimer = setTimeout(adjustPadding,250);
	});
	
	
	// no cycling through menu if scrolling after click on menu item
	straightscroll = false;

	$('#submenu a[href^="#"]').click(function(e){
		var href = $(this).attr('href');
		if(href.length < 2) {
			return false;
		} else {
			straightscroll = true;
			$('#submenu li a').removeClass('active');
			$(this).addClass('active');
			e.preventDefault();
			$target = $( href );
			// $target.css('background','red');
			st = $target.offset().top - $('#navigation').outerHeight() - 10;
			$('html, body').animate({ scrollTop: st}, 500, function(){ straightscroll = false; }); //, 'easeInOutQuad');
		}
	});

	$(window).scroll( $.throttle( 0, function(){
		if(straightscroll) return;
		// $('div.scrolltitle').css('background', 'none');
		$mv = $('#content').mostVisible('.scrolltitle');
		if($mv.length) {
			$('#submenu a').removeClass('active');
			$('#submenu a[href=#'+ $mv.attr('id') +']').addClass('active');
			// $mv.css('background','red');
		}
	}));

	
	
	
	// set up slideshows
	
	if($('#images').length > 0) {

		slideCount = $('#images div.slide').length;
	
		if( slideCount > 1 ) {
		
			lastSlide = false;
		
			function onBefore(curr,next,opts) {
				var nextNo = $(next).attr('id').substr(5);
				$('#imagecounter').html( nextNo + noConn + opts.slideCount );
				if(nextNo == opts.slideCount) lastSlide = true;
				else lastSlide = false;
			}
			
			$('#images div.inner').cycle({ 
				fx: 'scrollHorz',
				slideExpr: 'div.slide',
				prev:   'a#prev', 
				next:   'a#next', 
				timeout: 0,
				speed: 450
				,fit: 1
				// , after: onAfter
				, before: onBefore
			});
	
		} else if (slideCount == 1) {
	
			lastSlide = true;
	
	
			$('#imagecounter').html( 1 + noConn + 1 );
	
		}
	
		if(slideCount > 0) {
	
			$(document).keydown(function(e){
				if(e.which == 37) { // left
					$('#images div.inner').cycle('prev');
				} else if (e.which == 39) { // right
					if( lastSlide && $('#nextlink').attr('href') ) document.location.href = $('#nextlink').attr('href');
					else $('#images div.inner').cycle('next');
				}
			});	
	
		}	
	
	} // set up slideshows end

	

	// set up referenzen table	
	
	if($('#referenzen').length > 0) {
		
		getValue = function(what) {
			v = $(what).children('a').html();
			if( v == null) v = $(what).html();
			// if( (v.substr(0,1) == '"') || v.substr(0,1) == '„'  ) v = v.substr(1);
			v = v.replace(/[^a-zA-Z 0-9]+/g,'')
			return v.toLowerCase()
		}
		comparator = function(a,b) { return getValue(a).localeCompare(getValue(b)); };
		reverse_comparator = function(a,b) { return getValue(b).localeCompare(getValue(a)); };
	
		// $('table#referenzen td.title').sortElements(comparator, function() { return this.parentNode; });
		
		$('a#sort_title').click(function(e){
			$this = $(this);
			e.preventDefault();
			if( $this.hasClass('active') ) {
				$('#submenu a').removeClass('active').removeClass('reverse');
				$this.addClass('reverse');
				$('table#referenzen td.title').sortElements(reverse_comparator, function() { return this.parentNode; });
			} else {
				$('#submenu a').removeClass('active').removeClass('reverse');
				$this.addClass('active');
				$('table#referenzen td.title').sortElements(comparator, function() { return this.parentNode; });
			}
		});

		$('a#sort_client').click(function(e){
			$this = $(this);
			e.preventDefault();
			if( $this.hasClass('active') ) {
				$('#submenu a').removeClass('active').removeClass('reverse');
				$this.addClass('reverse');
				$('table#referenzen td.client').sortElements(reverse_comparator, function() { return this.parentNode; });
			} else {
				$('#submenu a').removeClass('active').removeClass('reverse');
				$this.addClass('active');
				$('table#referenzen td.client').sortElements(comparator, function() { return this.parentNode; });
			}
		});


		$('a#sort_type').click(function(e){
			$this = $(this);
			e.preventDefault();
			if( $this.hasClass('active') ) {
				$('#submenu a').removeClass('active').removeClass('reverse');
				$this.addClass('reverse');
				$('table#referenzen td.type').sortElements(reverse_comparator, function() { return this.parentNode; });
			} else {
				$('#submenu a').removeClass('active').removeClass('reverse');
				$this.addClass('active');
				$('table#referenzen td.type').sortElements(comparator, function() { return this.parentNode; });
			}
		});

		$('a#sort_date').click(function(e){
			$this = $(this);
			e.preventDefault();
			if( $this.hasClass('active') ) {
				$('#submenu a').removeClass('active').removeClass('reverse');
				$this.addClass('reverse');
				$('table#referenzen td.date').sortElements(reverse_comparator, function() { return this.parentNode; });
			} else {
				$('#submenu a').removeClass('active').removeClass('reverse');
				$this.addClass('active');
				$('table#referenzen td.date').sortElements(comparator, function() { return this.parentNode; });
			}
		});

	} // set up referenzen table end





	// homepage: fix height and grid for small features

	if($('#small_features').length > 0) {
	
	
		$('#small_features div.small_feature:nth-child(even)').each(function(){
			$this = $(this);
			$prev = $(this).prev('div');
			ph = false; th = false;
			ph = $prev.height();
			th = $this.height();
			if(ph && th) {
				if(ph > th) $this.height(ph);
				else $prev.height(th);
			}
		});
	
		$('div.small_feature:nth-child(odd)').addClass('first'); 
		
		
		if( $('#content').hasClass('home') ) homepageAnimation();
		
	
	} // fix small features end



	// set up homepage slideshows
	
	if($('div.more_images').length > 0) {
	
	
		$('div.more_images').hide();
		$('a.more_images').click(function(e){

			$this = $(this);
		
			e.preventDefault();
		
			ssBefore = function(curr,next,opts) {
				var nextNo = $(next).attr('id').substr(5);
				$ssCounter.html( nextNo + noConn + opts.slideCount );
				$ssCaption.html( $(next).attr('alt') );
				if(nextNo == opts.slideCount) lastSlide = true;
				else lastSlide = false;
			}
		
		
			
			var $mi = $( $(this).attr('rel') );
			
			if( $mi.hasClass('active') ) {
				// its open
				$mi.slideUp(400).removeClass('active');
				// kill slideshow
				$('div.slideshow').cycle('destroy');
				// closed arrow
				$this.removeClass('active');
				
				
								
			} else {
				// close open ss			
				$('div.more_images.active').slideUp(400).removeClass('active');
				// kill other slideshows
				$('div.slideshow').cycle('destroy');
				// remove open arrows
				$('a.more_images').removeClass('active');
				
				// LOAD CONTENT HERE, THE FOLLOWING WILL BE CALLBACK
				
				$mi.slideToggle(400).addClass('active');
				// init slideshow
				$ss = $mi.children('div.inner').children('div.slideshow');

				// open arrow
				$this.addClass('active');
				
				$ssCounter = $mi.find('span.ssCounter');
				$ssCaption = $mi.find('p.ssCaption');
				
				$ss.cycle({ 
					fx: 'scrollHorz',
					slideExpr: 'img',
					prev:   $mi.find('a.prev'), 
					next:  $mi.find('.next'),  
					timeout: 0,
					speed: 400
					,fit: 1
					// , after: onAfter
					, before: ssBefore
				});
				
			}
			
			return false;
		});
		
		
	} // set up homepage slideshows end



	// assign aktuell classes

	if($('span.aktuell').length > 1) {
		currentclass = 1;
		maxclass = 4;
		$('span.aktuell').each(function(){
			$(this).addClass('aktuell-'+currentclass);
			currentclass++;
			if(currentclass > maxclass) currentclass = 1;
		})
	} // end assign aktuell classes
	
	
	
	$('div.archive').hide();
	$('div.archivelink a').click(function(e){
		e.preventDefault();
		$(this).toggleClass('active');
		// $(this).parent('div').children('a').toggle();
		var href = $(this).attr('href');
		$(href).slideToggle(500);
	});
	
	
	$('#more-downloads').hide();
	$('a.more_downloads').click(function(e){
		e.preventDefault();
		$(this).toggleClass('active');
		var href = $(this).attr('href');
		$(href).slideToggle(500);
	});

	
	if($('#download_form').length > 0) {
	
		// do not hide if there are errors or a non-ajax link is clicked
		if (!window.show_form) $('#download_form').hide();
		
		$('a.closedownloadform').click(function(e){
			e.preventDefault();
			$('#download_form').fadeOut(300);
		})
	
		$('a.downloadlink').click(function(e){
			if(!has_cookie) {
				e.preventDefault();
				bits = $(this).attr('href').split('/');
				pk = parseInt(bits[bits.length-2]);
				$('#download_form #download').val(pk);	
				$('#download_form').fadeIn(300);
			}
		});
		
		
		$('#download_form').submit(function(e){
			// e.preventDefault();
			$('#download_form').fadeOut(500, function(){
				// reload page
				window.location.href = window.location.pathname;
			});
		});
		
		
		
	} // end download form setup


	// scroll to hash

	if( parent.location.hash != '') {
		var $target = $( parent.location.hash );
		if(! $target.length ) return;
		var st = $target.offset().top - $('#navigation').outerHeight() - 10;
		$('html, body').animate({ scrollTop: st}, 500, function(){ straightscroll = true; });
	}




});
