/**********************
 * Script for page logic
 * - Loads pages
 * - Cycles and fades backgrounds
 * - Manages and resizes background
 */

/***
 * Variables
 */
var activePage   = 'home';  // Active page variable; defaults to home
var marginBottom = 100;		// Margin-Bottom value for the resize script
var mainheight	 = '';		// Height of the #main element


/***
 * PageController - load a page and mange menu-active items
 * @param ids - the ID-string of the clicked page
 */
function getPage(page)
{
	// Set page variable
	activePage = page;
	
	// Remove 'active' class from menu-listitem & -active from menu-image
	$('#mainMenu li').removeClass('active');
	Cufon.refresh(); 
	// Start hiding current content
	$('#main').slideUp('medium', function(){
		// User information - Loader if page load takes to long
		timer = setTimeout('setLoader()', 1000);
		
		// load the url to main
		$('#main').load('./request/'+ page, function(){
			//replace texts
			Cufon.refresh(); 
			
			$('#main').height('').css('overflow', 'hidden');
			$('#main').slideDown('medium', function(){
				setImage(page);
				//Reset loader
				clearTimeout(timer);
				setLoader(false);
				//Set main-element's height
				mainheight = $('#main').height();
			});
		});
	});

	// Add 'active' to parent li & -active to the menu-image
	$('[href=#'+ page +']').parent().addClass('active');
}



/***
 * Manage the background image objects
 * @param page - the active page
 */
function setImage(page)
{
	// Determine image corresponding to page
	var activeImage = 0;
	$.each(pages, function(index, value) { 
		if (value.ids == page)
			activeImage = value.file;
	});
	
	// De we have a new image OR are is the home page active
	if (activeImage > 0  ||  activePage == 'home')
	{
		// Determine current active image
		current = $('#mainbgcontainer .active');
	    if (current.length == 0)
	    	current = $('#mainbgcontainer img:first');

	    // Add the (first) image as a new one
	    if (current.length == 0)
	    {
	    	var image = (activePage == 'home')
	    		?  getImage(pages[0].ids, pages[0].file)
	    		:  getImage(page, activeImage);
	    	$('#mainbgcontainer').append( image );
	    	image.addClass('active')
	    		.css({opacity: 1.0})
				.load(function(){
					resizebg();
					if (activePage == 'home')
						setTimeout('setImage()', 6000);
				});
	    }
	    
	    // Otherwise, start fading
	    else
	    {
	    	if (activePage == 'home')
	    	{
	    	    // Determine current page index
	    	    activeIndex = -1;
	    		for (var i=0; i<pages.length; i++)
	    			if (current.attr('id') == 'bg_'+pages[i].ids)
	    				activeIndex = i;
	    		
	    		// Determine the next
	    	    activeIndex++;
	    		if (pages[activeIndex] == undefined)
	    			activeIndex = 0;
	    		
	    		// Get next image
	    		var next = getImage(pages[activeIndex].ids, pages[activeIndex].file, current);
	    	}
	    	else
	    	{
		    	// Move all container images to inactive container, except the active
		    	$('#otherbgContainer').append( $('#mainbgcontainer img:not(.active)') );
		    	// Get the new image
		    	var next = getImage(page, activeImage, current);
	    	}
	    	
	    	// Add next to active container
	    	$('#otherbgContainer img').removeClass('active');
	    	
	    	// Only work with images if images are not equal
	    	if (current.attr('src') != next.attr('src'))
	    	{
	    		$('#mainbgcontainer').append( next );
	    		
		    	// Start fading the images when image is loaded
	    		if (next[0].complete)
	    			fadeInPhoto(next, current);
	    		else
	    			next.load(function(){ fadeInPhoto(next, current) });
	    	}
	    }
	}
}



/***
 * Function to fade two pictures
 * @param imgNew - the new image
 * @param imgOld - the active image
 */
function fadeInPhoto(imgNew, imgOld)
{
	// If image is not loaded yet, re-execute this function when it is loaded
//	if (!imgNew[0].complete)
//	{
//		imgNew.load(function(){
//			fadeInPhoto(imgNew, imgOld)
//		});
//		return;
//	}
	
	// Set the old image
	imgOld.addClass('last-active')
		.removeClass('active')
		.css({opacity: 1.0});
	
	// Animate the new image over the old
	imgNew.css({opacity: 0.0})
	    .addClass('active')
	    .animate({opacity: 1.0}, 500, function(){
	    	// On complete: remove old and resize new
		   imgOld.removeClass('last-active');
		   $('#otherbgContainer').append( imgOld );
		   resizebg();
		   
		   // While page is home, keep on running
		   if (activePage == 'home')
			   setTimeout('setImage()', 6000);
	    });
}



/***
 * Create a background image object
 * @param page - Page, used for html id
 * @param id - File id for the image
 * @param referenceImg - if supplied, used to copy width, height & margin-left
 * @return <img> object
 */
function getImage(page, id, referenceImg)
{
	//Check if he already exists
	if ($('#bg_'+page).length > 0)
		return $('#bg_'+page);
	
	// Create image object, set parameters and return
	var img = $(document.createElement('img'))
		.attr('src', 'files/image/'+id) //FIX?:  + '?random=' + (new Date()).getTime())
		.attr('id',  'bg_'+page);
	
	// Use width, height & margin-left from an existing image object
	if (referenceImg  &&  referenceImg.length > 0)
		img.css({
			'width': referenceImg.css('width'),
			'height': referenceImg.css('height'), 
			'margin-left': referenceImg.css('margin-left') 
		});
		
	return img;
}



/***
 * Resize background
 * Keep dimensions, fill whole screen
 */
function resizebg()
{
   //Get viewport sizes
   var win_w = $(window).width();
   var win_h = $(window).height();
   var fc_w  = $('.siteWidth').width();

   //Image size 100% of viewport, or always the width of the site
   var w = (win_w > fc_w) ? win_w : fc_w;
   $('#mainbgcontainer img').css({'width': w});

   //If image height smaller than viewport, enlarge image
   var h = $('#mainbgcontainer .active').height();
   var compare_h = win_h - marginBottom;
   
   if (h <= compare_h)
      $('#mainbgcontainer img').css({'height':compare_h, 'width':'auto'});
   
   //Else use auto-height from corresponding width
   else
      $('#mainbgcontainer img').height('auto');
   
   //Set margin-left to center image
   $('#mainbgcontainer img').css('margin-left',  parseInt( (-1 * $('#mainbgcontainer .active').width()) / 2 ) );
}



/***
 * Set loading image
 */
function setLoader(status)
{
	if (status == true  ||  status == undefined)
		$('#loading').html('<img src="gfx/ajax-loader.gif" title="loading page" />');
	else
		$('#loading').html('');
}


/***
 * Readmore link
 */
function readMore()
{
	$('#main')
		.animate({
			height: 450
		}, 400, function(){
			$('#main').css('overflow', 'auto');
			$('#main .siteWidth').css('padding-left','35px');
			$('.read-more').slideUp(200);
		})
		
	$('#extra-content')
		.slideDown(function(){
			$('#main').scrollTo($('#extra-content'), 800);
		});
}

/***
 * Readless link
 */
function readLess()
{
	$('#extra-content').slideUp();
	$('.read-more').slideDown(0);
	$('#main').animate({
		height: mainheight+'px'
	});
	$('#main .siteWidth').css('padding-left','20px');
	$('#main').css('overflow', 'hidden');
}



/***
 * Connect functions to events
 */

// Start with determining page from URL and run that page
$(document).ready(function(){
	// Get main height
	mainheight = $('#main').height();
	
	var urlPage = document.location.toString();
	if (urlPage.match('#'))
	{
		var myAnchor  = urlPage.split('#')[1];
		getPage(myAnchor);
	}
	else
		getPage('home');
});

//Connect resizebg-function to onLoad & onResize events
$(window).resize(resizebg);
$(window).load(function(){
	resizebg();
});

