var slide;
var beam;
var currentSlide;
var navBounce;
var navSlide;

window.addEvent('load', function() {
	getCurrentSlide();
	initializeSildes();
	initializeSliding();
	initializeAnchors();
   
	startSlidingPages();
});

window.addEvent('resize', function() {
	
	if(navBounce) resizeSlide.toElement(currentSlide);
	
});

function startSlidingPages()
{
	// IE6 bugfixing
	if(Browser.Engine.trident4)
	{
		$('navigation').setStyle('display', 'block');
		
		if(navBouncing)
		{
			navBounce.hide();
			navSlide.hide();
		}
	}
	
	// Jump to start position
	beam.toElement(currentSlide);
}

function getCurrentSlide()
{
	// Check if there is an anchor and set the currentSlide to the anchor or the first slide
	var anchor=document.location.hash.substring(1);
	if(anchor && $(anchor)) currentSlide=anchor;
	else currentSlide=$(document.body).getElement('div.slide').id;
}

function initializeAnchors()
{
	// Set up navigation FX for slide in
	if(navBouncing)
	{
		navBounce=new Fx.Slide('navigation', {
			duration: 1000,
			transition: Fx.Transitions.Bounce.easeOut
		}).hide();
	
		// Set up navigation FX for slide out
		navSlide=new Fx.Slide('navigation', {
			duration: 200,
			transition: Fx.Transitions.Quad
		}).hide();
	}
	
	// Get Page location
	var winLocation=urldecode(document.location.href.match(/^[^#]*/)[0]+'#');

	// Browse navigation Links ...
	var navCounter=0;
	$$('div#navigation a').each(function(element) {		
		// ... and set IDs
		var elementLink=urldecode(element.href);
		targetSlide=elementLink.replace(winLocation, "");
		element.set('id', 'nav'+targetSlide);

		navCounter++;
	});
	
	// Set navigation width to center the navigation
	if(navCenter)
	{
		navEntryWidth=$('nav'+targetSlide).getStyle('width').toInt()+$('nav'+targetSlide).getStyle('margin-left').toInt()+$('nav'+targetSlide).getStyle('margin-right').toInt();
		$$('div#navigation ul').setStyle('width', (navEntryWidth*navCounter)+'px');
	}
	
	// Browse through all Links ...
	$$('a').each(function(element) {
		
		// Check if the link contains an anchor to this page
		var elementLink=urldecode(element.href);
		if(elementLink.indexOf("#")!=-1 && elementLink.indexOf(winLocation)==0 && elementLink.length>winLocation.length)
		{
			// Check if the anchor positions exists
			var targetSlide=elementLink.replace(winLocation, "");
			if(targetSlide && $(targetSlide)) 
			{
				// Set the click action
				element.addEvent('click', function(e) {
					new Event(e).stop();
					
					if(currentSlide!=targetSlide)
					{
						// Toggle active CSS classes
						$$('div#navigation a').removeClass('active');
						$('nav'+targetSlide).addClass('active');
				
						// Set the current slide and jump there with a delay of 200ms
						currentSlide=targetSlide;
						var startSlide=function() { slide.toElement(targetSlide) };
						startSlide.delay(200);
				
						// Hide navigation
						if(navBouncing) navSlide.slideOut();
						else $('navigation').fade('out');
					
						// Hide head
						$('head').fade('out');
					}
				});
			}
		}
		else if(elementLink.indexOf("#")!=-1 && elementLink.indexOf(winLocation)==0)
		{
			// Set the click action
			element.addEvent('click', function(e) {
				new Event(e).stop();
			});
		}
	});

	// Set the active CSS class for the current slide
	$('nav'+currentSlide).addClass('active');
}

function initializeSliding()
{
	// Set Slidestyle according to the settings
	if(slideStyle=="linear") slideStyle=Fx.Transitions.Quad.easeInOut;
	else if(slideStyle=="dynamic") slideStyle=Fx.Transitions.Cubic.easeOut;
	else if(slideStyle=="bounce") slideStyle=Fx.Transitions.Bounce.easeOut;
	
	// Define new standard slide
	slide=new Fx.Scroll(window, {
		duration: slideDuration,
		transition: slideStyle,
		wheelStops: false,
		onStart: function() {
			appendElementsTo(currentSlide);
		},
		onComplete: function() {
			// Show navigation
			if(navBouncing) navBounce.slideIn();
			else $('navigation').fade('in');
			
			// Show head
			$('head').fade('in');
			
			// Set anchor
			document.location.hash=currentSlide;
		}
	});
	
	
	// Define instant move slide
	beam=new Fx.Scroll(window, {
		duration: 0,
		wheelStops: false,
		onStart: function() {
			appendElementsTo(currentSlide);
		},
		onComplete: function() {
			// Show navigation
			if(navBouncing) navBounce.slideIn();
			else $('navigation').fade('in');
			
			// Set anchor
			document.location.hash=currentSlide;
		}
	});
	
	
	// Define resize slide
	resizeSlide=new Fx.Scroll(window, {
		duration: 100,
		wheelStops: false
	});
}

function initializeSildes()
{
	// Set body dimensions
	document.body.style.width=gridCols+'00%';
	document.body.style.height=gridRows+'00%';
	
	// IE6 bugfixing
	if(Browser.Engine.trident4)
	{
		$$('div.slide').setStyle('width', (100/gridCols)+'%');
		$$('div.slide').setStyle('height', (100/gridRows)+'%');
	}
	
	// Browse through slides ...
	colCounter=1;
	rowCounter=1;
	$$('div.slide').each(function(element) { 

		// .. and set the position according to the grid
		element.setStyle('left', (colCounter-1)+'00%');
		element.setStyle('top', (rowCounter-1)+'00%');
		
		if(colCounter>=gridCols)
		{
			colCounter=1;
			rowCounter++;
		}
		else colCounter++;
	});
	
	// Set window position to 0 / 0
	window.scrollTo(0, 0);
}

function appendElementsTo(currentSlide)
{
	// Append navigation to new slide
	if(navPos=="top") $('navigation').inject($(currentSlide), 'top');
	else $('navigation').inject($(currentSlide).getElement('div.box'), 'top');
	
	// Append content box head to new slide
	$('head').inject($(currentSlide).getElement('div.box'), 'top');
}

function urldecode( str ) {
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir
    
    var histogram = {};
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urlencode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
 
    for (replace in histogram) {
        search = histogram[replace]; // Switch order when decoding
        ret = replacer(search, replace, ret) // Custom replace. No regexing   
    }
    
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = decodeURIComponent(ret);
 
    return ret;
}
