/*

Main Javascript file
Author: John K.
Version: 1.0

*/

var base_url = window.location.host;

jQuery(window).resize(function() {

	// Fix the background
	resize_bg();

});

jQuery(document).ready(function($){

	Cufon.replace('#contact-sitemap, #copyright, .stylish, #header ul, #content h2, fieldset h3',{
		hover: true,
		textShadow: '0 1px rgba(0, 0, 0, 0.6)'
	});
	
	// Load background
	load_bg();
	
	// Tabs
	$('.tab-content').hide()
	$('.tab-content.visible').show()
	
	fixOverviewList();
	
	// Open all external links and PDF in new window
	$("a[href^='http:']:not([href*='" + base_url + "']), a[href$='.pdf']:not([href*='" + base_url + "']), a[href$='.pdf']").live('click', function() {
		$(this).attr('target','_blank');
	});
	
})

// Load background
function load_bg() 
{
	// Set background image
	var body = $('body');
	
	if(body.hasClass('index')) 
	{
		var bg_image = 'http://'+base_url+'/images/background/home2.jpg';
	}
	else
	{
		r = Math.floor(Math.random()*4);
		var bg_image = 'http://'+base_url+'/images/background/bg'+r+'.jpg';
	}
		
	// Add image to bg if empty
	if($('#bg img').length == 0) 
	{
		$('#bg').append('<img />');
	}
	
	$('#bg img').attr('src', bg_image);

	// Preload background image
	var cache = [];
	
	var cacheImage = document.createElement('img');
	cacheImage.src = $('#bg img').attr('src');
	cache.push(cacheImage);
	
	// Reveal background
	$("#bg img").one('load', function() {
		// fade in bg
		$('#bg').fadeIn(1500);
		// resize to fit the screen
		resize_bg();
		
	}).each(function() {
	  if(this.complete) $(this).load();
	});
	
	// Still is not loaded?
	setTimeout(function() {
	
		$('#bg').fadeIn(1500);
		resize_bg();

	}, 2500);
}

function resize_bg() {

	// Set background height = window height
	$('#bg').height($(window).height());
	
	var image = $('#bg img')
	
	// calculate width/height ratio to keep proportions on resize
	var ratio = $(image).width()/$(image).height();
		
    // If bg width is smaller than window width
	if($(image).width() < $(window).width()) {
		$(image).width($(window).width());
		$(image).height($(image).width()/ratio);
	}
		
    // If bg height is smaller than window height
	if($(image).height() < $(window).height()) {
		$(image).height($(window).height());
		$(image).width($(image).height()*ratio);
	}
	
    // Position to center of the screen
	$(image).css({
		'margin-left':'-'+($(image).width()-$(window).width())/2+'px',
		'margin-top':'-'+($(image).height()-$(window).height())/2+'px'
	})
	
	// Make sure cont has same height as bg
	$('#cont').height($('#bg').height());
}

// Fix overview list
function fixOverviewList(){
	items = $('ul.models-overview li')
	for(i=3;i<items.length;i+=4){
		$(items[i]).addClass('no-border');
	}
}

