var bgImg_1 = "#bgImg_1";
var bgImg_2 = "#bgImg_2";
var current;
var iNext;
var aLength;
var imageSource;
var active = 0;
var iWidth = 2560;
var iHeight = 1600;

$(document).ready(function(){
	current = randomNumber;
	iNext = current;
	aLength = image.length;
	if(aLength >= 1){
 		resizeElements();
		showFirstImage();
	};

	$('#bg_button').click(function(){
		$('#wrapper').fadeOut(600);
		$('#bg_button_return').fadeIn(100);
	});
	$('#bg_button_return').click(function(){
		$('#wrapper').fadeIn(600);
		$('#bg_button_return').fadeOut(100);
	});
});

function imgSource(){
	imageSource = image[iNext];
	return imageSource;
};

function resizeElements() {
	var wWidth = $(window).width();
	var wHeight = $(window).height();
	var iTop = (wHeight-40)/2;
	var iLeft = (wWidth-40)/2;
	$('#loader').stop().css({top: iTop, left: iLeft});
};

function showFirstImage() {
	imageSource = imgSource();
	$(bgImg_1)[0].src = imageSource;
	resizeImage();
	$(bgImg_1).fadeIn(950, function(){
		if(runn == "yes"){
			preloadNextImage();
		};
	});
	$('#loader').stop().fadeOut('slow');
};

function resizeImage() {
	var wWidth = $(window).width();
	var wHeight = $(window).height();
	var wRatio = wHeight / wWidth;
	var iRatio = iHeight / iWidth;
	
	if (iRatio > wRatio) {
		var nHeight = (wWidth / iWidth) * iHeight;
		var nWidth = wWidth;
	} else {
		var nWidth = (wHeight / iHeight) * iWidth;
		var nHeight = wHeight;
	}
	
	nTop = 0 - ((nHeight - wHeight) / 2);
	nLeft =  0 - ((nWidth - wWidth) / 2);

	$('.bg_image').css({height: nHeight, width: nWidth}).css({top: nTop, left: nLeft});
	resizeElements();
};

function preloadNextImage(){
	if(iNext != (aLength-1)){iNext += 1;}else{iNext = 0;};
	imageSource = imgSource();
	$(bgImg_2).show();
	$(bgImg_2)[0].src = imageSource;
	setTimeout(function(){showNextImage()}, 900);
};

function showNextImage(){
	current = iNext;
	resizeImage();
	$('#bgImg_1').fadeOut(4000, function(){
		$(bgImg_1)[0].src = imageSource;
		$('#bgImg_1').show();
		preloadNextImage();
	});
	phpUpdate();
};




$(window).resize(function(){
	resizeImage();
});
