$(document).ready(function() {
	
	initMainNav();
	fixedMenu();
	assignEventHandlers();
	initSlideshows();
	
	$('a[rel="_blank"]').click(function(){
        window.open(this.href);
        return false;
    })
	
	if ( $('a.step_forward').size() > 0 ) {  initSteps(); }
});


function initSteps () {
 	
	var curStep = 1;
	
	$('a.step_forward').each( function() {  
		
		$(this).bind('click', function() {
		
			var id = parseInt($(this).attr('id').replace(/stepButton_/g, ''));
			
			//console.log('checking ctl0:group' + id + ': ' + $('input:radio[name=ctl0group' + id + ']').val() );
			
			// find out if radio for this step is checked
			if ( $('#ctl0_group' + id + '_0').attr('checked') == false && $('#ctl0_group' + id + '_1').attr('checked') == false ) {
							  
				if ($('#errorMessage').size() > 0) { } else {
					$('#formAssistent').prepend('<div id="errorMessage">Bitte beantworten Sie zuerst die Frage.</div>');
				}
				
			} else {
			
				if ($('#errorMessage').size() > 0) $('#errorMessage').remove('#errorMessage');
				
				$('#step_' + id).hide();
				
				if ( id < 8 ) {
				
					$('#step_' + (id + 1)).css('display','block');
					
				} else if (id == 8) {
					
					var countYes   = 0;
					var resultHTML = "<table>";
					
					// prepare result
					for (i=1; i <= 8; i++) {
					
						// is true
						
						var radioVal = $('input[name="ctl0group' + i + '"]:checked').val(); 
						//console.log('checking ctl0group' + i + ': ' + $('input[name=ctl0group' + i + ']:checked').val() );
						
						var radioTitle = $('#step_' + i + ' .fragenh2').text();
						var radioExtension = $('#step_' + i + ' .radioExtension').text();

						if ( radioVal == 'ja' ) {
						
							resultHTML += "<tr><td valign='top'><img src='/common/images/fragen_haken.gif' /></td><td><b>" + radioTitle + "</b><br />" + radioExtension + "</td></tr>";
							//console.log('radioVal: ' + radioVal);
							
							countYes++;
						}
					}
					
					resultHTML += "</table>";

					$('#step_final #resultTable').append(resultHTML);
					//console.log('found ' + countYes + ' positive answers...');
					
					if (countYes > 0) {
						$('#step_final .resultText').text('Ihr Ergebnis: Ihr Kind zeigt Symptome einer m\u00f6glichen Kuhmilchallergie. Bitte sprechen Sie den behandelnden Kinderarzt darauf an.');
					}
					else {
						$('#step_final .resultText').text('Ihr Ergebnis: Ihr Kind zeigt keines der typischen Symptome einer Kuhmilchallergie. Wenn Sie sich trotzdem unsicher sind, sprechen Sie bitte mit Ihrem Kinderarzt.');
					    $('#step_final .fragenh2').hide();
						$('#step_final .fragenBodyDown').hide();
					}
					
					$('#step_final').css('display','block');
					
				} else {}
				
				//console.log(id + ' is the current step...try to move to ' + (id + 1));
			} 
		});
		
	});
}


function initMainNav () {
	
	// nav_main - equally stretch items to fill available space
	
		var holderWidth = $("#main").width();
		var itemsWidth = 0;
		var counter = 0;
		
		var unmodItemsWidth = 0;
		$("#nav_main>ul>li").each(function(index) {
			unmodItemsWidth += $(this).width();
		});
		
		while (holderWidth > (itemsWidth+unmodItemsWidth) || counter < 100) {
			counter++;
			
			$("#nav_main>ul>li").each(function(index) {
				itemsWidth ++;
				if (holderWidth >= (itemsWidth+unmodItemsWidth)) {
					$(this).width($(this).width()+1);
				}
			});
		}
}

var objToScroll = ($.browser.webkit) ? 'body' : 'html';
var space = 23;

function fixedMenu() {
	if ($('#pageregion_left').size()==1 && !($.browser.msie && $.browser.version == "6.0") ) {
		var nav = $("#pageregion_left");
		var offset = $(nav).offset();
		var navHeight = $(nav).outerHeight();
		var docHeight = $(document).height();
		var headerHeight = $("#pageregion_top").outerHeight(true);
		var footerHeight = $("#footer").outerHeight() + space;
		
		var areas = new Object;
		areas.top = new Object;
		areas.main = new Object;
		areas.bottom = new Object;
		
		areas.top.start = 0;
		areas.top.end = offset.top - space;
		areas.top.end = offset.top;
		areas.main.start = areas.top.end;
		areas.main.end = docHeight - footerHeight;
		areas.bottom.start = areas.main.end;
		areas.bottom.end = docHeight;	
		
		$(window).scroll(function() {
									   
			var scrollPos = $(objToScroll).scrollTop();
			
			// in the main -> fix nav
			if (scrollPos >= areas.main.start && scrollPos + space + navHeight <= areas.main.end) {
				$(nav).css({
					"position": "fixed",
					"top": space
				});
			} 
			// stop nav before footer
			else if (scrollPos + space + navHeight >= areas.bottom.start) {
				$(nav).css({
					"position": "relative",
					"top": docHeight - headerHeight - footerHeight - navHeight - 20
				});
			}
			// in the header -> reset
			else {
				$(nav).css({
					"position": "",
					"top": ""
				});
			}
		});
	}
}

function assignEventHandlers () {

	// nav_main
		$("#nav_main>ul>li").mouseenter(function() { 
 
				if ($(this).find("ul").is(':not(:animated)')) $(this).find("ul").slideDown('fast', function() { $(this).parent().children("a").addClass("open"); }).show(); 
 
			}).hover(function() {  
				$(this).children("a").addClass("open");
			}, function(){
				//$(this).children("a").removeClass("open");
		}).mouseleave(function() { 

				$(this).find("ul").slideUp('slow', function() { $(this).parent().children("a").removeClass("open"); });  ;  
 
			});  
		
	// website select

		$('#websites').mouseenter(function() {
			if ($("#websites").is(':not(:animated)')) {
				$('#websites').removeClass("closed").addClass("open");
				$('#websites').animate({
					//height: '205px'
					height: '279px'
				}, 200);
			}
		});
		
		$('#websites').mouseleave(function() {
			$('#websites').animate({
				height: '25px'
			}, 200, function() {
				$('#websites').removeClass("open").addClass("closed");
			});
		});
}

// Easing equation, borrowed from jQuery easing plugin
// http://gsgd.co.uk/sandbox/jquery/easing/
jQuery.easing.easeOutQuart = function (x, t, b, c, d) {
	return -c * ((t=t/d-1)*t*t*t - 1) + b;
};

var teaserScrollOptions = {
			target:'.teaserPane',
			items:'.teaserPaneItem', // Selector to the items ( relative to the matched elements, '.teaserPane' in this case )
			navigation:'.teaserPaneControl a',
			duration:300,
			easing:'easeOutQuart',
			force:true
		}

function initSlideshows() {

	// add serialScroll to homepage slideshow
		if ($('#slideshow').size()==1) {
		
			/*	var $prev = $('#slideshowHolder span.slidePrev'),
				$next = $('#slideshowHolder span.slideNext');
			*/
		
			$('#slideshow').serialScroll({
				items:'.slide',
				//prev:'#slideshowHolder span.slidePrev',
				//next:'#slideshowHolder span.slideNext',
				navigation:'#slideControl .slideNav',
				duration:600,
				stop:true,
				lock:false,
				cycle:false,
				force: true,
				easing:'easeOutQuart',
				onBefore: function (e, elem, $pane, $items, pos ){
					//those arguments with a $ are jqueryfied, elem isn't.
					e.preventDefault();
					if( this.blur ) this.blur();
					/*
					$prev.add($next).removeClass("slideEnd");
					if( pos == 0 )
						$prev.addClass("slideEnd");
					else if( pos == $items.length-1 )
						$next.addClass("slideEnd");
					*/
				}
			});
		}
	
	// add serialScroll to every .teaserScroll
		$('.teaserScroll').serialScroll(teaserScrollOptions);
}
