jQuery.noConflict();

var pages; // vertically oriented pages (example: pages = [page1][page2][page3][page4];
var currentPage = 0; // index of the currently displayed page (example: currentPage = 2 -> [page3])

// whether the currently displayed page has additional horizontally oriented pages 
var hasLeft = false; 
var hasRight = false; 

// the standard height of the page
var landingHeight = 700;

// prevents the page changing DURING the the animation effects (for example if the hyperlinks are pressed too fast)
var scrollLock = false; 
var animationSpeed = 500;
var overflow = 137;

jQuery(document).ready(function() {
	makeUpdate();
	navigation();
	arrowSliding();
	folgeseiten();
	buttonHover();
	/* sets the height of the LAST landingpage qual to the current height of the page*/
	jQuery('.landingpage:last .bg').css('height', getPageSize()[3]-137);
	jQuery(window).resize(function(){
		jQuery('.landingpage:last .bg').css('height', getPageSize()[3]-137); // speziell für die letze landingpage
	});
});

/**
	function makes the update of global values
	NOTE: shoud normally be called after each page changing (both horizontally and vertically) 
*/
function makeUpdate(){
	pages = getPages(); 	
	checkAdditionalPages();
}

/**
	function manages the hyperlinks of the main menu above
*/
function navigation(){
	if(jQuery.cookie("ziel")){ // über weiterleitung
		var tempTarget = jQuery.cookie("ziel");
		jQuery.cookie("ziel", null, {path: '/'});
		scrollLock = true;
		makeUpdate();
		goToTarget(parseInt(tempTarget));
	} else { // per hand für die FolgeSeite
		if(jQuery('#mainNav li ul li.active').parent().index() != -1){ // es gibt ein activer link im untermenü
			setActiveLink(jQuery('#mainNav li ul li.active').parent().parent().index());
		} else {
			setPage(0);
		}
	}
	
	jQuery('#mainNav>li>a').click(function(){
		if(!scrollLock){
			var linkIndex = jQuery(this).parent().index();
			if(linkIndex < pages.length){
				scrollLock = true; 
				goToTarget(linkIndex);	
			}
		}
	});
}

function changePage(location){
	var split = location.split("#");
	jQuery.cookie("ziel", split[1], {path: '/'});
	window.location.pathname = split[0]+"/";
}	
/**
	function makes the vertical scrolling to the target page and updates the global values
	@param:  target [0..n]
	@example goToTarget(2) -> changes to the page3;
	NOTE: this is one of the main functions. It is allways called when it comes to the vertical navigaton
*/

function goToTarget(target){	
	currentPage = target;
	var targetOffset = pages[target].offset().top; 	
	jQuery('html, body').stop().animate({scrollTop: targetOffset}, animationSpeed, function(){
		checkAdditionalPages();
		setActiveLink(target);
		scrollLock = false;
	});
}

function setPage(target){	
	currentPage = target;
	setActiveLink(target);
	checkAdditionalPages()
}

/**** BEGIN: THE FOLLOWING FUNCTIONS ARE RESPONSIBLE FOR THE HORIZONTAL NAVIGATION *****/

/**
	checks if the currentPage has additional pages and updates the global values
*/
function checkAdditionalPages(){
	var leftChild = jQuery(pages[currentPage]).children('.left').children('.landingpage'); 
	var rightChild = jQuery(pages[currentPage]).children('.right').children('.landingpage'); 
	if(leftChild.length > 0){
		hasLeft = true;
		getMiniPictureLeft();
		jQuery('.arrow.left').show();
	} else {
		hasLeft = false; 
		jQuery('.arrow.left').hide();
	}
	if(rightChild.length > 0){
		hasRight = true;
		getMiniPictureRight();
		jQuery('.arrow.right').show();
	} else {
		hasRight = false;
		jQuery('.arrow.right').hide();
	}
}

/**
	function manages the horizontal sliding of the pages
*/
function arrowSliding(){
	animateArrows();	
	jQuery('#content .arrow.right').click(function(){
		if(!scrollLock){
			scrollLock = true;
			slideToRight();
		}
	});
	jQuery('#content .arrow.left').click(function(){
		if(!scrollLock){
			scrollLock = true; 
			slideToLeft();
		}
	});
}

/**
	the function is resposible for the animation of the arrows (hover effect)
*/
function animateArrows(){
	var right = jQuery('#content .arrow.right');
	var left = jQuery('#content .arrow.left');

	right.mouseover(function(){
		jQuery(this).stop().animate({right: 0}, 500);
	});
	right.mouseout(function(){
		jQuery(this).stop().animate({right: -65}, 500);
	});
	right.click(function(){
		jQuery(this).stop().animate({right: -65}, 100);
		jQuery(this).children('.miniPicture').children('img').attr('src', '');
	});
	
	left.mouseover(function(){
		jQuery(this).stop().animate({left: 0}, 500);
	});
	left.mouseout(function(){
		jQuery(this).stop().animate({left: -65}, 500);
	});
	left.click(function(){
		jQuery(this).stop().animate({left: -65}, 100);
		jQuery(this).children('.miniPicture').children('img').attr('src', '');
	});
}

function getMiniPictureRight(){
	var arrow = jQuery('.arrow.right');
	var tempPicture = pages[currentPage].children('.right').children('.landingpage:first').children('.container').children('.mini').children('img').clone();
	var wrapper = "<div class='miniPicture'></div>";
	wrapper = jQuery(wrapper).prepend(jQuery(tempPicture));
	tempPicture.load(function(){
		arrow.children('.miniPicture').replaceWith(wrapper);
	});
}

function getMiniPictureLeft(){
	var arrow = jQuery('.arrow.left');
	var tempPicture = pages[currentPage].children('.left').children('.landingpage:last').children('.container').children('.mini').children('img').clone();
	var wrapper = "<div class='miniPicture'></div>";
	wrapper = jQuery(wrapper).prepend(jQuery(tempPicture));
	tempPicture.unload(function(){
		arrow.children('.miniPicture').append();
	});
	tempPicture.load(function(){
		arrow.children('.miniPicture').replaceWith(wrapper);
	});
}

/**** END: THE FUNCTIONS ARE RESPONSIBLE FOR THE HORIZONTAL NAVIGATION *****/

/**
	function makes an animated sliding to the left and update the tree structure of the landing pages
	NOTE: should normally be called ONLY if a currentPage has additional pages on the right
*/
function slideToRight(){
	jQuery('.arrow').hide();
	var old = pages[currentPage]; 
	var neu = old.children('.right').children('.landingpage:first');
	old.wrap("<div class='tempWrapper'></div>");
	neu.insertAfter(old);
			
	old.css('position', 'absolute');
	neu.css('position', 'absolute');
	
	
	old.stop().hide('slide', {direction: 'left'}, animationSpeed, function(){
		old.css('position', 'relative');
	});	
	neu.stop().show('slide', {direction: 'right'}, animationSpeed, function(){
		neu.css('position', 'relative');
		neu.unwrap();
		neu.append("<div class='left'></div><div class='right'></div>");
		neu.children('.right').replaceWith(old.children('.right'));	
		neu.children('.left').replaceWith(old.children('.left'));
		neu.children('.left').append(old);	
		makeUpdate();
		scrollLock = false;
		jQuery('.ui-effects-wrapper').remove();	
	});
	
}

/**
	function makes an animated sliding to the right and update the tree structure of the landing pages
	NOTE: should normally be called ONLY if a currentPage has additional pages on the right
*/

function slideToLeft(){
	jQuery('.arrow').hide();
	var old = pages[currentPage]; 
	var neu = old.children('.left').children('.landingpage:last');	
	old.wrap("<div class='tempWrapper'></div>");
	neu.insertAfter(old);

	old.css('position', 'absolute');
	neu.css('position', 'absolute');

	old.stop().hide('slide', {direction: 'right'}, animationSpeed, function(){
		old.css('position', 'relative');
	});	
	neu.stop().show('slide', {direction: 'left'}, animationSpeed, function(){
		neu.css('position', 'relative');
		neu.unwrap(); 
		neu.append("<div class='left'></div><div class='right'></div>");
		neu.children('.left').replaceWith(old.children('.left'));
		neu.children('.right').replaceWith(old.children('.right'));	
		neu.children('.right').prepend(old);			
		makeUpdate();			
		scrollLock = false;
		jQuery('.ui-effects-wrapper').remove();	
	});
	
}

/**
	function returns the modulo of 2 numbers an the rest
	example modulo(5, 102) -> [20, 2]
*/
function modulo(x, y){
	var counter = 0; 
	var temp, result;
	function mod(x, y){
	temp = y; 
		if(temp > x){
			temp = y - x; 
			counter++; 
			mod(x, temp); 
		} else {
			result =  new Array(counter, temp);;
		}
	}
	mod(x, y);
	return result;
}

/**
	function manages the keybord pressing and changes to new pages
*/	
jQuery(document).keydown(function(event){
	if(!scrollLock){
		switch(event.keyCode){
			case 40: // down
					if(currentPage < pages.length-1){ // nicht die letze seite
						scrollLock = true; 
						goToTarget(currentPage + 1);
					}
				break;
			case 38: // up
					if(currentPage > 0){ // nicht die letze seite
						scrollLock = true; 
						goToTarget(currentPage - 1);
					}
				break;
			case 39: // right
					if(hasRight){
						scrollLock = true;
						slideToRight();
					}
				break;
				
			case 37: // left
					if(hasLeft){
						scrollLock = true;
						slideToLeft();
					}
				break;
				
			case 116: 
					scrollLock = true;
					window.scrollTo(0, 0);
				break;
			default:
				break;
		}
	} else {
	
	}
});


/**
	The function returns a 2-dimensional array with pages depending on the html stucture
*/
function getPages(){
	var temp = new Array(); 
	var element, child; 
	var elementIndex, childIndex;

	var counter = 0; 
	jQuery('#content').children('.landingpage').each(function(){
		element = jQuery(this); 
		temp[counter] = element;
		counter++;
	});
	return temp; 
}

function buttonHover(){
	jQuery('.button').mouseover(function(){
		jQuery(this).children('.button_small_left').css('background-image', 'url(/img/button_small_left_hover.png)');
		jQuery(this).children('.button_small_middle').css('background-image', 'url(/img/button_small_middle_hover.png)');
		jQuery(this).children('.button_small_right').css('background-image', 'url(/img/button_small_right_hover.png)');
		jQuery(this).children('.button_big_left').css('background-image', 'url(/img/button_big_left_hover.png)');
		jQuery(this).children('.button_big_middle').css('background-image', 'url(/img/button_big_middle_hover.png)');
		jQuery(this).children('.button_big_right').css('background-image', 'url(/img/button_big_right_hover.png)');
	}).mouseleave(function(){
		jQuery(this).children('.button_small_left').css('background-image', 'url(/img/button_small_left.png)');
		jQuery(this).children('.button_small_middle').css('background-image', 'url(/img/button_small_middle.png)');
		jQuery(this).children('.button_small_right').css('background-image', 'url(/img/button_small_right.png)');
		jQuery(this).children('.button_big_left').css('background-image', 'url(/img/button_big_left.png)');
		jQuery(this).children('.button_big_middle').css('background-image', 'url(/img/button_big_middle.png)');
		jQuery(this).children('.button_big_right').css('background-image', 'url(/img/button_big_right.png)');
	});
}

/**
 * getPageSize() by quirksmode.com
 *
 * @return Array Return an array with page width, height and window width, height
 */
function getPageSize() {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
	}
	
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}	
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	
	// pageWidth = document.body.clientWidth;
	// pageHeight = document.body.clientHeight;

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
}


/**
 * getPageScroll() by quirksmode.com
 *
 * @return Array Return an array with x,y page scroll values.
 */
function getPageScroll() {
	var xScroll, yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}
	arrayPageScroll = new Array(xScroll,yScroll);
	return arrayPageScroll;
}

/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

