var container = $('#container'); 
var containerInner = $('#container_inner'); 
containerInner.height(container.height()+'px');

var siteTitle = 'WebKonzepte';
var transitionTime = 1000;
var ajaxActive = false;

var actionOpenHeight = 400;


$('a[href="'+currentUrl+'"]').addClass('current');

$.address.change(function(event) {  
	href = event.value;
	if (href == '/' || href == currentUrl)
		return;
	load(href);
});

$('html').addClass('jquery');
$('#main').attr('aria-live','assertive').attr('aria-relevant','all');
Galleria.loadTheme('js/galleria/themes/classic/galleria.classic.min.js');

var header = $('#pagehead');
var hpos = header.offset();
header.css('position','fixed').css('left',hpos.left + 'px');


initAccordion();


$('nav a').click(function(event)
{
	if ($(this).attr('href') == currentUrl)
		return false;
	event.preventDefault();
	if (ajaxActive)
		return;
	ajaxActive = true;
	$('nav a').removeClass('current');
    $.address.value($(this).attr('href'));  
});


Shadowbox.init({
	overlayOpacity: 0.8,
	skipSetup: true
});


function initShadowbox(parent)
{
	parent = parent !== undefined ? parent+' ':'';
	$(parent+'img[rel="lightbox"]').each(
			function() {
				$(this).removeAttr('rel').wrap('<a rel="lightbox" href="' + $(this).attr('src')+'" title="'+ $(this).attr('alt') +'"/>');
			}
	);
    Shadowbox.setup(parent+"a[rel^='lightbox']", {});
};
initShadowbox(); 

function initGalleria(parent)
{
	parent = parent !== undefined ? parent+' ':'';
	$(parent + '.galleria').galleria({
		width:'100%',
		height:500,
	    lightbox: true
	});
}
initGalleria();

function initForm(parent)
{
	parent = parent !== undefined ? parent+' ':'';
	$(parent+'#kontakt').submit(function(form)
	{
		if (ajaxActive)
			return;

		// TODO: hier validieren

		ajaxActive = true;	
		var form = $(this);
		
		form
			.attr('aria-busy','true')
			.prepend('<span class="loading" aria-busy="true"></span>')
			.children('fieldset')
			.animate({ 'opacity' : 0.4 },1000);
		$('.loading')
			.width(form.width())
			.height(form.height());
		
		var action = form.attr('action');
		var data = form.serialize() + '&ajax=1';
		
		$.post(
				action,
				data,
				function(data)
				{
					form
						.before(data)
						.fadeOut('slow',function(){form.remove();});
					result = $('#result');
					var rHeight = result.height();
					result
						.css('height','0')
						.css('position','static')
						.animate({'height': rHeight+'px'},1000);
					ajaxActive = false;
				}
		);
		return false;
 
	}); 

}
initForm();





function load(url,fast) 
{
	currentUrl = url;
	if (url.indexOf('?')>= 0)
		var coupler = '&';
	else
		var coupler = '?';
	url = url + coupler + 'ajax=1';

	var main = $('#main');
	if (fast)
	{
		main.load(url);
		return;
	}
	var width = main.width();
	var outerWidth = main.outerWidth(true);
	var height = $(document).height(); 

	main.wrapInner('<div id="deleter"></div>');
	
	main.append('<div id="loader" aria-busy="true"><div id="loaderInner"></div></div>');
	var loader = $('#loader');
	var loaderInner = $('#loaderInner');
	loader.width((outerWidth+200)+'px').css('z-index',999);
	loaderInner
	//	.css('height', height + 'px')
		.css('width', width + 'px')
		.css('left', '-' + width + 'px')
	//	.css('transform','scale(0.1)') 
	//	.css('transform','rotate(180deg)') 
		;

	$('nav a').removeClass('current');
	$('a[href="'+currentUrl+'"]').addClass('current');

	$.get(url,function(text){
		var title = text.match(/<title>(.*)<\/title>/);
		text = text.replace(title[0],'');
		setTitle(title[1]);
//		loaderInner.css('display','none').fadeIn();
		loaderInner.append(text);

		initAccordion('#loaderInner');
		initGalleria('#loaderInner');
		initActionbox('#loaderInner');
		
		

		var winHeight =  $(window).height();
		var newHeight = Math.max(loaderInner.height(), winHeight);

//		containerInner.animate({height: newHeight+'px'},transitionTime);
		containerInner.height( newHeight+'px');

		loaderInner.height( Math.max(loaderInner.height(), winHeight) + 'px');

		$('#deleter').fadeOut('slow', function(){$('#deleter').remove(); });
				
	    $(loaderInner).animate({
	    	//	rotate: '0deg',
    		//	scale: '1',
	    		left: Math.floor((outerWidth-width)/2)+'px',
	    		boxShadow: '0 0 0 #fff'
	    	},
	    	transitionTime,
	    	function(){
	    		main.html();
	  	    		
	    		main.append(loaderInner.html());
   		
	    		loader.remove();
	   
	    		initForm();
	    		initGalleria();
	    		initShadowbox();
	    	//	initDetails();
	    		initGlossary();
	    		initAccordion2();
	       		ajaxActive = false;
	       		
	    	}
	    );
    
	});
}


function setTitle(title)
{
	if (title.toLowerCase() != siteTitle.toLowerCase())
		title = siteTitle + ': ' + title;
	$.address.title(title);
}

function initDetails() 
{
	if($('html').hasClass('no-details'))
	    // Loop through all `details` elements
	    $('details').each(function() {
	
	      // Store a reference to the current `details` element in a variable
	      var $details = $(this),
	          // Store a reference to the `summary` element of the current `details` element (if any) in a variable
	          $detailsSummary = $('summary', $details),
	          // Do the same for the info within the `details` element
	          $detailsNotSummary = $details.children(':not(summary)'),
	          // This will be used later to look for direct child text nodes
	          $detailsNotSummaryContents = $details.contents(':not(summary)'),
	          // This will be used later on
	          open = this.getAttribute('open');
	
	      // If there is no `summary` in the current `details` element…
	      if (!$detailsSummary.length) {
	        // …create one with default text
	        $detailsSummary = $(document.createElement('summary')).text('Details').prependTo($details);
	      }
	
	      // Look for direct child text nodes
	      if ($detailsNotSummary.length !== $detailsNotSummaryContents.length) {
	        // Wrap child text nodes in a `span` element
	        $detailsNotSummaryContents.filter(function() {
	          // Only keep the node in the collection if it’s a text node containing more than only whitespace
	          return (this.nodeType === 3) && (/[^\t\n\r ]/.test(this.data));
	        }).wrap('<span>');
	        // There are now no direct child text nodes anymore — they’re wrapped in `span` elements
	        $detailsNotSummary = $details.children(':not(summary)');
	      }
	
	      // Hide content unless there’s an `open` attribute
	      // Chrome 10 already recognizes the `open` attribute as a boolean (even though it doesn’t support rendering `<details>` yet
	      // Other browsers without `<details>` support treat it as a string
	      if (typeof open == 'string' || (typeof open == 'boolean' && open)) {
	        $details.addClass('open');
	        $detailsNotSummary.show();
	      } else {
	        $detailsNotSummary.hide();
	      }
	
	      // Set the `tabIndex` of the `summary` element to 0 to make it keyboard accessible
	      $detailsSummary.attr('tabIndex', 0).click(function() {
	        // Focus on the `summary` element
	        $detailsSummary.focus();
	        // Toggle the `open` attribute of the `details` element
	        typeof $details.attr('open') !== 'undefined' ? $details.removeAttr('open') : $details.attr('open', 'open');
	        // Toggle the additional information in the `details` element
	        $detailsNotSummary.toggle(0);
	        $details.toggleClass('open');
	      }).keyup(function(event) {
	        if (13 === event.keyCode || 32 === event.keyCode) {
	          // Enter or Space is pressed — trigger the `click` event on the `summary` element
	          // Opera already seems to trigger the `click` event when Enter is pressed
	          if (!($.browser.opera && 13 === event.keyCode)) {
	            event.preventDefault();
	            $detailsSummary.click();
	          }
	        }
	      });
	
	      
	    });
}
//initDetails();

function initGlossary()
{
	$('[aria-describedby^="#glossary-"]').cluetip({
								local:true,
								width:400,
								cursor: 'pointer',
								arrows: false,
								attribute: 'aria-describedby',
								dropShadow: false,
								cluetipClass: 'wktip'
							})
							.addClass('glossaryAnchor')
	$('details').each(function(){
			var summary = $(this).children('summary');
			var title = summary.html();
			summary.remove();
			var txt = $(this).html();
			$(this).remove();
			$('#glossary').append('<div id="'+$(this).attr('id')+'"><h2>'+title+'</h2>'+txt+'</div>');
	});

	
}
initGlossary();


var actionPrePosition;
var actionOpenHeight = 400;
var actionboxWidthFactor = 0.8;
var autoId=0;

function initActionbox()
{
	$('.actionbox')
		.addClass('actionboxLoaded')
		.addClass('rightOut')
		.prepend('<span class="actionOpen"><a href="#" onclick="return actionOpen(this);">lesen &hellip;</a></span>')
		.each( function(){ if ((h = $(this).attr('data-height'))) $(this).css('height', h); })
		;
	$('.actionbox[id=]').each(function(i){$(this).attr('id', 'autoId'+(++i));} );
}
initActionbox();

function actionOpen(select) 
{
    actionClose();
	var oldBox = $('#'+ $(select).parent().parent().attr('id'));
	var newBox = oldBox.clone();
	var newBoxId = 'actionShow'+oldBox.attr('id');
	newBox.attr('id', newBoxId);
	oldBox.after(newBox);
	newBox.children('.actionOpen').remove();

	var contentCol = $('#main');
	var bigWidth = Math.floor( contentCol.width()*actionboxWidthFactor );
	
	var actionPrePosition = oldBox.position();
	
	var bigbox = $('#'+newBoxId);	
	var tmp = bigbox.html();
	bigbox
		.html('')
		.prepend('<div id="bbscroller'+newBoxId+'" class="scroller"><div class="scrollerInner"></div></div>')
		.css('width', bigWidth + 'px')
		.css('height','auto')
		.addClass('actionShow');
	$('#bbscroller'+newBoxId)
		.css('height','100%')
		.children('.scrollerInner').html(tmp);
	
	var winHeight = $(window).height();
	var scrollTop = $(window).scrollTop();
	var contentTop = contentCol.offset().top;
	var contentHeight = $('#bbscroller'+newBoxId).height();
	var newHeight = Math.min(actionOpenHeight, contentHeight+30, winHeight-80);
	var viewportPosition = winHeight/2 - newHeight/2; 
	newPosition = scrollTop + viewportPosition;
	var leftShift =  bigWidth;
	bigbox
		.prepend('<span class="actionClose" id="actionClose'+newBoxId+'"><a href="#" onclick="return actionClose(this)">&times;</a></span>')
		.css('top',actionPrePosition.top + oldBox.height()-10)
		.css('height','0')
		.attr('py',Math.round(actionPrePosition.top + (oldBox.height()/2)))
		.attr('px',Math.round(actionPrePosition.left + (oldBox.width()/2)))
		.attr('parent',oldBox.attr('id'))
		.animate({
			width:bigWidth+'px',
			height: newHeight + 'px',
			top:newPosition + 'px',
			right:'30px'
		},1000,'swing',function(){})
		;
	oldBox
		.animate( {opacity:'0.3'}, 1000 )
		.css('filter','alpha(opacity=30)')
		.children('.actionOpen').hide();
	return false;

}
function actionClose() {
	openbox = $('.actionShow');
	if (openbox.length)
		openbox.animate({
				width:'0px',
				height:'0px',
				top:openbox.attr('py'),
				left:openbox.attr('px'),
				padding:'0'
			},1000,'swing',function(){$(this).remove()}
		);
		$('#'+openbox.attr('parent'))
			.animate({ opacity:'1' },1000)
			.css('filter','alpha(opacity=100)')
			.children('.actionOpen').show();
			;
	return false;
}

function accordion(selectId, speed)
{
	var openIt = $('#'+selectId);
	var closeIt = $('.ac-open');
	if  (openIt.hasClass('ac-open'))
		return;	
	var closedHeight = openIt.height();
	
	openIt.css('height','auto');
	var openHeight = openIt.outerHeight();

	openIt.css('height',closedHeight+'px');
	openIt.animate({ height: openHeight+'px'}, 'slow', function(){
		openIt.addClass('ac-open').removeClass('ac-closed').unbind('click');
	});
	openIt.children('.ac-opener').fadeOut();
	closeIt.animate({ height: closedHeight+'px'}, 'slow', function(){
		closeIt.addClass('ac-closed').removeClass('ac-open').bind('click',function(){accordion($(this).attr('id'),'slow');});
		
		var pos = openIt.offset();
		var openY = pos.top;
		var winHeight = $(window).height();
		var winScrollTop = $(window).scrollTop();
		if (openY < winScrollTop || openY > winScrollTop+winHeight*0.7)
			$('html,body').animate({scrollTop: openY-40	}, 1000);	
	});
	closeIt.children('.ac-opener').fadeIn();
	

	return false;
}
function initAccordion(parent)
{
	parent = parent !== undefined ? parent+' ':'';
//alert('#'+parent + '.accordion[id=]#'); $("#parent").children("div :not([name])");
	$(parent + '.accordion:not([id])').each(function(i){
//		alert(i);
		$(this).attr('id', 'autoId'+(++i));
		if (!$(this).hasClass('ac-open'))
			$(this).addClass('ac-closed');
	});
	$(parent + '.ac-closed').on('click',function(){accordion($(this).attr('id'),'slow');});
	$(parent + '.accordion').each(function(i){$(this).append('<span class="ac-opener"><span>lesen &hellip;</span></span>');});
	
}
function initAccordion2(parent)
{
	parent = parent !== undefined ? parent+' ':'';
	$(parent + '.ac-closed').bind('click',function(){accordion($(this).attr('id'),'slow');});
}
