
var bgCurrent = -1;
var bgAmount = 0;

$(document).ready(function()
{
	//bg
    onResize();
    $(window).resize(function()  { onResize(); });
    backgroundAnimation();
	if (bgAmount > 1) {
		setInterval(backgroundAnimation, 8000);
	}
});

function onResize() {
	var winWidth = $(window).width();
	var winHeight = $(window).height();
	var winAspectRatio = winWidth / winHeight;

	//console.log($('div#container').height() + "::"+winHeight);
	var top = (winHeight - $('div#container').height()) / 2 - 20;
	top = top > -1 ? top : 0;
	$('div#container').css({top: top+'px'});
	
	var bgs = $('div#background img.backgroundImage');
	bgAmount = bgs.length;
	
	for (var i=0; i<bgs.length; i++) {
		img = bgs[i];
		imgWidth = $(img).width();
		imgHeight = $(img).height();
		imgAspectRatio = imgWidth / imgHeight;
		//console.log(imgWidth+":"+imgHeight);
		
		if (winAspectRatio > imgAspectRatio) {
			//console.log('width');	 
			var height = (winWidth / imgWidth) * imgHeight;
			var width = winWidth;
		} else {
			// scale pic to fit window height	
			//console.log('height');	
			var height = winHeight;
			var width = (winHeight / imgHeight) * imgWidth;
		}
		
		left =  (width - winHeight) / 2;

		//$(img).css({left: left});
		$(img).css({height: height, width: width});
	}
}

function backgroundAnimation() {
	var next = getRandom(0, bgAmount-1);  
	while (next == bgCurrent && bgAmount > 1) {
		next = getRandom(0, bgAmount-1);
	}
	var bgs = $('div#background img.backgroundImage'); 
	if (bgCurrent > -1) {
		$(bgs[bgCurrent]).fadeOut(1100); 	
	}
	//console.log(next+"::"+bgCurrent);
	$(bgs[next]).fadeIn(2700);
	bgCurrent = next;		
}


function getRandom( min, max ) {
        if( min > max ) {
                return( -1 );
        }
        if( min == max ) {
                return( min );
        }
        return( min + parseInt( Math.random() * ( max-min+1 ) ) );
} 

