
//show or hide the button to re-open the content box after it was closed
function showOpenButton() {
	$('#contentlayer').hide('fold',{size: 60},1000,function() {
		$('#openButton').show('drop',{ direction: "up" },'500','');
	});		
}
function hideOpenButton() {
	$('#openButton').hide('drop',{ direction: "up" },'500',function() {
		$('#contentlayer').show('fold',{size: 60},1000,'')
	});	
}

//show or hide the slider for the content box regarding the content-length
var sliderVisible = false;
function adjustSlider() {
	if (($("#content-scroll").attr("scrollHeight") - $("#content-scroll").height()) == 0) {
		$("#content-slider").slider( "disable" );
		$(".ui-slider-handle").animate({height: 0});
		sliderVisible = false;
		$("#content-slider-pane").fadeOut();
	} else {
		if (!sliderVisible) {
			$("#content-slider").slider( "value" , [100] );
			$("#content-slider").slider( "enable" );
			$(".ui-slider-handle").animate({height: '40px'});
			$("#content-slider-pane").fadeTo(600,0.2);
			sliderVisible = true;
		}
	}
}
function slideToTop() {
	 $('#content-slider').slider( 'value' , [100] );
}

//add the click-eventlisteners to the subcontent-boxes to open and close them
var lastOpenSubContentBox = null;
var lastOpenSubSubContentBox = null;
function addContentBoxEventListeners() {
	
	$('.subcontent strong').click( function() {
		//close all subcontent boxes
		$('.subcontent').removeClass('active');
		$('.subcontent').children("strong").removeClass('active');
		$('.subcontent').children(".subcontent_more").slideUp('500', function() {
				adjustSlider();
			} );
		
		//open if not already open
		if (lastOpenSubContentBox != this) {
			$(this).parent().toggleClass('active');
			$(this).toggleClass('active');
			//toggle the first sub-div
			$(this).nextAll(".subcontent_more:first").slideToggle('500', function() {
				adjustSlider(); //adjustSlider() just in case the content-lenght crosses the limit for the slider to display or hide
			} );
			lastOpenSubContentBox = this;
			//$("#mp3player_label").html("offset:"+$(this).parent().position.top);
		} else {
			lastOpenSubContentBox = null;
			//all subcontents closed, restore the page-imageset
			setBackgroundImages(pages[pageindex].pics);
		}

	} );
	
	$('.subsubcontent strong').unbind("click");
	$('.subsubcontent strong').click( function() {
		
		//close all subsubcontent boxes
		$('.subsubcontent').removeClass('active');
		$('.subsubcontent').children("strong").removeClass('active');
		$('.subsubcontent').children(".subsubcontent_more").slideUp('500', function() {
				adjustSlider();
			} );
		
		//open if not already open
		if (lastOpenSubSubContentBox != this) {
			$(this).parent().toggleClass('active');
			$(this).toggleClass('active');
			//toggle the first sub-div
			$(this).nextAll(".subsubcontent_more:first").slideToggle('500', function() {
				adjustSlider();
			} );
			lastOpenSubSubContentBox = this;
		} else {
			lastOpenSubSubContentBox = null;
		}
		
	} );
	
}


//load a new content page into the content box via ajax
var pageindex = 0;
var lasttouchpos = 0;
function loadpage(index) {	
	//load html content via ajax and adjust sliders if a new page was selected
	if (pageindex != index) {
		pageindex = index;
		$("#content-holder").load("loadcontent.php", "name="+pages[pageindex].name, function() {
				$("#content-scroll").attr({scrollTop: 0 });
				$("#content-slider").slider( "value" , [100] );
				adjustSlider();
				addContentBoxEventListeners();
		}  );
		
		//set the url hash for deep linking
		window.location.hash = pageindex;
		
		//deactivate all hover-events on the menu images
		setMenuHoverFunction();
		//set active menu entry and deactivate its hover-event		
		act_menuentry = $("#navbar #"+pages[pageindex].name+" img");
		
		act_menuentry.unbind('mouseenter mouseleave');
		act_menuentry.each(
				function() {
					this.src = this.src.replace("_f1.gif","_f2.gif");
				}
			);
		
		
		//load new background images		
		setBackgroundImages(pages[pageindex].pics);
		//open content box if it is hidden and close close-button
		if($('#contentlayer').is(':hidden')) {
			hideOpenButton();
		}
		lasttouchpos = 0;
	}
}


//function to load a new set of background-images
var BackgroundImageRotator = null;
var backgroundImagesList;
var backgroundImageLastIndex = 0;
function setBackgroundImages(new_backgroundImagesList) {
		
	if (backgroundImagesList != new_backgroundImagesList) {

		backgroundImagesList = new_backgroundImagesList
		backgroundImageLastIndex = 0;
		
		$('#backimage_img_temp').unbind('load');
		$('#backimage_img_temp').bind('load', function() {
			$('#backimage_img_temp').stop(true,true).fadeIn(700, function() {
				$('#backimage_img').attr('src', "content_images/"+backgroundImagesList[backgroundImageLastIndex]);
				//if last image is reached, start again from first element in list
				if (backgroundImageLastIndex >= backgroundImagesList.length-1) {
					backgroundImageLastIndex = 0;
				} else {
					backgroundImageLastIndex++;
				}
			});	
			$('#backimage_img_temp').fadeOut(700);
		});
		
		//load first new image
		rotateBackgroundImage();
		//stop the rotator
		clearInterval(BackgroundImageRotator);
		//start rotator only if there is more than one image to rotate
		if (backgroundImagesList.length > 1) {
			//start the background-image-rotator with the desired interval
			BackgroundImageRotator = setInterval("rotateBackgroundImage()", 4000);
		}
	}
	
}

//load images into background, select next image in list each time the function is called (by interval)
function rotateBackgroundImage() {

	if (backgroundImagesList[backgroundImageLastIndex] != "") {		
		//set the new source of the temp image which is hidden. the "load" event of the temp image will trigger everything else!
		$('#backimage_img_temp').stop(true,true);
		$('#backimage_img_temp').attr('src', "content_images/"+backgroundImagesList[backgroundImageLastIndex]);	
	}
}


//step through all the content-pages back and forth (use the predefined jscript array)
function nextPage() {
	if (pageindex < pages.length-1) {
		pageindex_load = pageindex+1;
	} else {
		pageindex_load = 0;
	}
	loadpage(pageindex_load);
	
}
function prevPage() {
	if (pageindex > 0) {
		pageindex_load = pageindex-1;
	} else {
		pageindex_load = pages.length;
	}
	loadpage(pageindex_load);
}


//MP3 Player
var playItem;

function playListInit(autoplay) {
	if(autoplay) {
		playListChange( 0 );
	} else {
		playListConfig( 0 );
	}
}
function playListChange( index ) {
	if (playItem != index) {
		playListConfig( index );
		$("#mp3player").jPlayer("play");
	}
}
function playListConfig( index ) {
	playItem = index;
	$("#mp3player_label").html("[ "+myPlayList[playItem].name+" ]");
	$("#mp3player").jPlayer("setFile", myPlayList[playItem].mp3);
} 	
function playListNext() {
	var index = (playItem+1 < myPlayList.length) ? playItem+1 : 0;
	playListChange( index );
}
function playListPrev() {
	var index = (playItem-1 >= 0) ? playItem-1 : myPlayList.length-1;
	playListChange( index );
}


//content slider event handlers for slide and click
function handleSliderChange(e, ui) {
	var maxScroll = $("#content-scroll").attr("scrollHeight") - $("#content-scroll").height();
 	$("#content-scroll").stop(true,true).animate({scrollTop: (100-ui.value) * (maxScroll / 100) }, 500 );
}	
function handleSliderSlide(e, ui) {
	var maxScroll = $("#content-scroll").attr("scrollHeight") - $("#content-scroll").height();
	$("#content-scroll").attr({scrollTop: (100-ui.value) * (maxScroll / 100) });
}


//hover-effects for the main menu
function setMenuHoverFunction() {
	
	//unbind all events...
	$("#navbar a img").unbind('mouseenter mouseleave');
	//reset all hover-states
	$("#navbar a img").each(
		function() {
			this.src = this.src.replace("_f2.gif","_f1.gif");
		}
	)
	//... and re-bind them
	$("#navbar a img").hover(
		function() {
			this.src = this.src.replace("_f1.gif","_f2.gif");
		},
		function() {
			this.src = this.src.replace("_f2.gif","_f1.gif");
		}
	);
}

//set up objects after the page was fully loaded
$(document).ready(function() {
	
	//load background images for home
	setBackgroundImages(pages[0].pics);
	
	//predefine ajax parameters for content-page loads
	$.ajaxSetup({
	   cache: false,
	   type: "GET"	
	 });
	 
	//set main menu hover functions
	setMenuHoverFunction();
	//activate first menu entry and remove its hover-function
	firstMenuEntry = $("#navbar #"+pages[0].name+" img");
	firstMenuEntry.unbind('mouseenter mouseleave');
	firstMenuEntry.each(
		function() {
			this.src = this.src.replace("_f1.gif","_f2.gif");
		}
	);
	
	
	//initialize the content slider for the content box
	$("#content-slider").slider({
		animate: 500,
		change: handleSliderChange,
		slide: handleSliderSlide,
		orientation: 'vertical',
		value: 100
	});
	
	//add scrollwheel functionality to the content slider
	$("#content-holder").mousewheel(function(event, delta) {
		var value = $("#content-slider").slider('option', 'value');
		
		if (delta > 0) { value += 10; }
		else if (delta < 0) { value -= 10; }
				
		// Ensure that its limited between 0 and 100
		value = Math.max(0, Math.min(100, value));
		$("#content-slider").slider('option', 'value', value);
		event.preventDefault();
			
	}); 
 
	//touch events for the page (prevent moving)
	document.body.ontouchmove = function(e){
		e.preventDefault();
	}
	//slide content box text with touch gestures
	document.getElementById("content-holder").ontouchmove = function(e){
		e.preventDefault();

	  if(e.touches.length == 1){ // Only deal with one finger
	    var touch = e.touches[0]; // Get the information for finger #1
	    var node = touch.target; // Find the node the drag started from
	    if (lasttouchpos > 0) {
			$("#content-scroll").attr({scrollTop: ($("#content-scroll").attr("scrollTop")+(lasttouchpos - touch.pageY) )});
			//$("#mp3player_label").html("touchY:"+touch.pageY+"<br>lastpost:"+lasttouchpos+"<br>scrolltop:"+$("#content-scroll").attr("scrollTop")+"<br>scrollamout:"+(lasttouchpos - touch.pageY));
	    }
		lasttouchpos = touch.pageY;
	  }
	}
	document.getElementById("content-holder").ontouchend = function(e){
		lasttouchpos = 0;
	}


	//show or hide the content slider (for home page)
	adjustSlider();
	
	//add listeners for the content-box-sections (for home page)
	addContentBoxEventListeners();
	
	
	//MP3 Player
	$("#mp3player").jPlayer({
		ready: function () {
			//autoplay music on page load
			playListInit(true);
		},
		volume: 50,
		oggSupport: false,
		preload: 'none',
		swfPath: "js",
		errorAlerts:true,
		nativeSuport:true
	})
	.jPlayer("onSoundComplete", function() {
		playListNext();
	});	
	
	$("#jplayer_back").click( function() {
		playListPrev();
		$(this).blur();
		return false;
	});
	$("#jplayer_fwd").click( function() {
		playListNext();
		$(this).blur();
		return false;
	});
	
	//deeplinking: load selected page when hash in url is set
	pagehash = window.location.hash.replace("#", "");
	pagehash = parseInt(pagehash);
	if (pagehash >=0 && pagehash <= pages.length) {
		loadpage(pagehash);
	}
	
	

});
